Get the last character with at() in JavaScript
Beginner · 3 min read
Getting the last character of a string comes up all the time: checking whether a sentence ends with a question mark, whether a word is plural, or what the final digit of a reference number is. For years the only way was a small sum, text[text.length - 1]. It works, but it is easy to get wrong and hard to read.
Modern JavaScript has a cleaner tool: the at() method. It accepts a negative number and counts from the end. In this tutorial you will use it to read the last character and the one before it, and you will meet the one value that trips it up. You only need to know what a string is and that its characters are numbered from 0.
Counting from both ends
The characters of 'Lagos' have positions from the front and, with at, from the back too:
L a g o s
0 1 2 3 4 counting from the front
-5 -4 -3 -2 -1 counting from the back
-1 is always the last character, -2 the one before it, and so on. A negative index is simply length plus that number: for 'Lagos', -1 means 5 + -1, which is index 4.
Here is the exercise. Have a go yourself first, or read on and we will build it together.
3 Count back from the end with at
easyGet the last character, and the one before it, without doing arithmetic on length.
Stuck? Three hints, smallest first
- 1.
ataccepts a negative index and counts from the right. - 2.
at(-1)is the last,at(-2)the one before it. - 3. Out of range it returns
undefined, the same way brackets do.
Step 1: the old way
Start with the version you will still see in plenty of code.
const word = 'Lagos';
console.log(word[word.length - 1]); // 's'
word.length is 5, and since positions start at 0, the last one is 4. It works, but every time you read it you have to do the sum in your head.
Step 2: the last character with at(-1)
Now the same thing with at.
const word = 'Lagos';
const lastChar = (text) => text.at(-1);
console.log('at(-1):', lastChar(word)); // at(-1): s
console.log(word.at(-2)); // 'o'
at(-1) says "one from the end", which is exactly what you meant. at(-2) is the one before it. There is no length and no subtraction to get wrong.
Step 3: positive indexes still work
at is not only for negatives. With a positive number it behaves just like square brackets.
const word = 'Lagos';
console.log(word.at(0)); // 'L'
console.log(word.at(3) === word[3]); // true
console.log(word.at(-1) === word[word.length - 1]); // true
The last line proves that at(-1) gives exactly what the old sum gave.
Step 4: go out of range
Ask for a position that doesn't exist, in either direction.
const word = 'Lagos';
console.log(word.at(-99)); // undefined
console.log(word.at(99)); // undefined
Past either end you get undefined, JavaScript's value for "nothing here". That is the same thing square brackets give you, so nothing new to learn.
Step 5: the -0 trap
Here is the surprise. JavaScript has a value written -0, and it counts as equal to 0.
const word = 'Lagos';
console.log(-0 === 0); // true
console.log(word.at(-0)); // 'L', the FIRST character
Since -0 is the same as 0, at(-0) reads position 0, the first character. You would rarely type -0 yourself. But imagine code that computes how far from the end to look:
const word = 'Lagos';
const fromEnd = (text, n) => text.at(-n);
console.log(fromEnd(word, 1)); // 's'
console.log(fromEnd(word, 0)); // 'L', not "nothing"
With n as 0, -n is -0, and you get the first character instead of an empty result. If n can ever be 0, check for that case yourself before calling at.
Step 6: compare with slice(-1)
slice(-1) also gets the last character: it cuts off the last one-character piece of the string. The two only differ when there is no character to get, as in an empty string:
console.log(JSON.stringify(''.slice(-1))); // "", an empty string
console.log(''.at(-1)); // undefined
slice always returns a string, even an empty one. at returns undefined when there is no character. JSON.stringify is only there so the empty string shows up when printed.
The full solution
Here is the complete answer, with lastChar, the old way next to it, and the -0 case printed so you can see it. Press Run to see the output.
const word = 'Lagos';
const lastChar = (text) => text.at(-1);
console.log('at(-1):', lastChar(word));
console.log('the old way:', word[word.length - 1]);
console.log('at(-0) :', word.at(-0), '<- the FIRST character, because -0 is 0');
Output
10 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 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('at(-1) is the last character', word.at(-1), 's');
test('at(-2) is the one before it', word.at(-2), 'o');
test('at(0) is the first', word.at(0), 'L');
test('positive indexes agree with brackets', word.at(3), word[3]);
test('too far back gives undefined', word.at(-99), undefined);
test('and so does too far forward', word.at(99), undefined);
test('it replaces the length arithmetic exactly', word.at(-1), word[word.length - 1]);
test('slice(-1) does the same job but returns a string', ''.slice(-1), '');
test('so on an empty string the two differ', ''.at(-1), undefined);
test('and at(-0) is the FIRST character, because -0 is 0', word.at(-0), 'L');
at exists so that text[text.length - 1] can stop being written. It works on arrays too, with the same rules.
The -0 case is the one to remember. -0 === 0 is true in JavaScript, so at(-0) is at(0) and returns the first character. Any code that computes an offset and might arrive at zero needs an explicit check rather than trusting the sign.
Common mistakes
- Using
text[-1]. Square brackets don't count from the end, so this isundefined. Usetext.at(-1). - Passing a computed
-nwhennmight be 0.at(-0)isat(0), the first character, not "nothing". - Assuming
atalways gives a string. Out of range it givesundefined, so calling.toUpperCase()on the result can throw.
Try it yourself
- Write
isQuestion(sentence)that returnstruewhen the last character is'?'. - Arrays have
attoo. Use it to get the last item of['red', 'green', 'blue']. - Fix
fromEnd(text, n)so thatfromEnd('Lagos', 0)returnsundefinedinstead of'L'.