The String charAt() method
By Flavio Copes
Learn how the JavaScript charAt() method returns the character at a given index in a string, and why an out-of-range index gives you an empty string back.
charAt() returns the character at the index i in a string. Indexes start at 0, so charAt(0) is the first character.
Examples:
'Flavio'.charAt(0) //'F'
'Flavio'.charAt(1) //'l'
'Flavio'.charAt(2) //'a'
JavaScript does not have a “char” type, so a char is a string of length 1. That’s what charAt() gives you back, a one-character string.
If you call it without an argument, the index defaults to 0:
'Flavio'.charAt() //'F'
The index is converted to a number if needed, so passing '2' works like passing 2. I don’t recommend relying on that, but it explains some surprising code you might find.
What happens with an out-of-range index?
If you give an index that does not match the string, you get an empty string:
'Flavio'.charAt(10) //''
'Flavio'.charAt(-1) //''
No error, no undefined. Just ''.
Notice this is different from accessing the string with square brackets:
'Flavio'[10] //undefined
Same question, two different answers. This matters when you check the result.
Watch out when checking the result
Here’s a bug I’ve seen in the wild. You switch from brackets to charAt(), and a check like this stops working:
const initial = 'Flavio'.charAt(10)
if (initial === undefined) {
//never runs: initial is '', not undefined
}
With charAt() the out-of-range result is '', which is falsy but not undefined. The strict comparison fails and the guard never triggers.
The fix is to check for a falsy value instead:
if (!initial) {
//runs for both '' and undefined
}
What about negative indexes?
charAt(-1) returns an empty string, it does not count from the end.
If you want “last character” behavior, use the at() method, which accepts negative indexes:
'Flavio'.at(-1) //'o'
For in-range indexes the two behave the same. Out of range they differ again: at() returns undefined where charAt() returns ''. charAt() has been around forever, at() is the more recent addition.
Want me to talk about your product? You can sponsor this site.
Related posts about js: