Get the first and last character of a string in JavaScript
Beginner · 3 min read
Reading one character from a string is a small job you'll do all the time: the first letter of a name for an avatar, the last character of a code to check it, a trailing slash on a web address. JavaScript gives you three ways to do it: charAt, square brackets, and the newer at. In the middle of a string they all agree. At the edges, past the end or with a negative position, they behave differently, and that's where bugs come from.
In this tutorial you will read the first and last character of the bus stop name 'Yaba' three ways, then test each one off the end and with a negative index. You need to know what a string and a method are.
Positions start at 0
Each character in a string has a position, called its index. The first character is at index 0, not 1:
Y a b a
0 1 2 3
So a string of length 4 has indexes 0 to 3. The last character is always at length - 1.
Three ways to read a character
stop.charAt(0): a method that has been in JavaScript from the start.stop[0]: square brackets, the same way you read an array item.stop.at(0): a newer method that also understands negative positions, counting back from the end.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
101 Reading one character: charAt, brackets and at
easyRead the first and last character of a bus stop name three ways — charAt, square brackets and at — then find out what each one does when the index is off the end or negative.
Stuck? Three hints, smallest first
- 1.
at(-1)is the last character; the other two know nothing about negative indices. - 2. Off the end, one of the three gives an empty string and the other two give
undefined. - 3. Before
atexisted, the last character wascharAt(length - 1).
Step 1: the first character
const stop = 'Yaba';
console.log(stop.charAt(0)); // Y
console.log(stop[0]); // Y
console.log(stop.at(0)); // Y
All three give 'Y'. For any position inside the string, they are interchangeable.
Step 2: the last character, the old way
Before at existed, the last character meant working out its index:
const stop = 'Yaba';
console.log(stop.charAt(stop.length - 1)); // a
console.log(stop[stop.length - 1]); // a
stop.length is 4, so length - 1 is 3, the last index. It works, but you have to write the string's name twice, and it's easy to forget the - 1.
Step 3: the last character with at
at accepts a negative index, which counts backwards from the end. -1 is the last character, -2 the one before it:
const stop = 'Yaba';
console.log(stop.at(-1)); // a
console.log(stop.at(-2)); // b
console.log(stop.at(-1) === stop.charAt(stop.length - 1)); // true
That's the whole reason at was added: at(-1) replaces the length - 1 dance.
Step 4: off the end
Now ask for index 9, past the end of a four-letter word:
const stop = 'Yaba';
console.log(stop.charAt(9) === ''); // true
console.log(stop[9]); // undefined
console.log(stop.at(9)); // undefined
They disagree. charAt gives an empty string ''. Brackets and at give undefined.
This matters more than it looks. Say you uppercase the result. stop.charAt(9).toUpperCase() quietly gives '', and the problem shows up somewhere else later. stop[9].toUpperCase() throws a TypeError right away, on the line that's wrong. A loud failure is usually easier to fix.
Step 5: a negative index
const stop = 'Yaba';
console.log(stop.charAt(-1) === ''); // true
console.log(stop[-1]); // undefined
console.log(stop.at(-1)); // a
Only at understands negatives. charAt(-1) treats it as out of range and gives ''. stop[-1] is not an error and not the last character either: the brackets look for a property named "-1", which doesn't exist, so you get undefined.
Step 6: at runs out at the front
Counting backwards also has an end:
const stop = 'Yaba';
console.log(stop.at(-4)); // Y
console.log(stop.at(-5)); // undefined
-4 is the first character of a four-letter word. -5 would be before the start, so it's undefined.
The full solution
The answer panel reads the first and last character with all three tools, then compares them off the end and with a negative index. Its checks cover each case, including at running out at the front. Press Run to see the output.
const stop = 'Yaba';
const first = stop.charAt(0);
const alsoFirst = stop[0];
const last = stop.at(-1);
const lastTheOldWay = stop.charAt(stop.length - 1);
console.log('off the end: ', [stop.charAt(9), stop[9], stop.at(9)]);
console.log('negative index:', [stop.charAt(-1), stop[-1], stop.at(-1)]);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('charAt(0) reads the first character', first, 'Y');
test('brackets read the same one', alsoFirst, 'Y');
test('at(-1) reads the last', last, 'a');
test('which is the length - 1 dance it replaces', last, lastTheOldWay);
test('past the end charAt gives an empty string', stop.charAt(9), '');
test('brackets give undefined instead', stop[9] === undefined, true);
test('and so does at', stop.at(9) === undefined, true);
test('a negative index means nothing to charAt or to brackets', [stop.charAt(-1), stop[-1] === undefined], ['', true]);
test('at counts backwards, and runs out at the front', [stop.at(-4), stop.at(-5) === undefined], ['Y', true]);
All three read the same character in the middle of a string and disagree completely at the edges, which is where bugs live. charAt off the end gives '', so stop.charAt(9).toUpperCase() quietly returns '' and the fault surfaces somewhere else; brackets and at give undefined, so the same line throws immediately. The loud failure is usually the kinder one.
stop[-1] is not an error and not the last character — it reads a property named "-1" that does not exist, so undefined. Only at understands negatives, which is the whole reason it was added. Also exercise 5, which rotated a string with slice; here the angle is a single position rather than a whole cut.
Common mistakes
- Using
stop[-1]for the last character. Brackets don't count from the end. Usestop.at(-1). - Forgetting the
- 1.stop[stop.length]is one past the end and givesundefined. - Assuming
charAtfails loudly. Off the end it gives'', which hides the bug. Check the length first if the index might be out of range.
Try it yourself
- Write
initial(name)that returns the first letter in upper case, and''for an empty name. - Write
endsWithSlash(url)usingat(-1). - Write
firstAndLast(text)that returns'Y...a'for'Yaba'. What should it return for a one-letter word?