charAt() vs bracket notation in JavaScript
Beginner · 4 min read
Reading a single character out of a string is something you will do constantly: the first letter of a name for an avatar, the last character of a word to check for an s, the next symbol while you walk through a line of text.
JavaScript gives you two ways to do it: square brackets, text[0], and a method, text.charAt(0). Most of the time they give the same answer. In this tutorial you will use both, then find the cases where they disagree, because that is where bugs come from. You only need to know what a string and a function are.
Positions start at 0
Each character in a string has a position number called its index. The first character is at index 0, the second at 1, and so on:
L a g o s
0 1 2 3 4
'Lagos' has 5 characters, so the indexes run from 0 to 4. The last index is always length - 1.
There is no "character" type
Some languages have a special type for a single character. JavaScript doesn't. When you read one character out of a string, you get back another string, just one character long. That means everything you know about strings still works on it.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
2 Read one character out
easyGet the first and last character of a word, with brackets and with charAt. Then ask both of them for a character that is not there.
Stuck? Three hints, smallest first
- 1. Bracket indexing reads like an array:
text[0]. - 2.
charAtdoes the same job but disagrees when the index is out of range. - 3. There is no character type in JavaScript, so what you get back is a one-character string.
Step 1: the first character with brackets
Put the index in square brackets after the string, the same way you would read an item from an array.
const word = 'Lagos';
const first = (text) => text[0];
console.log(first(word)); // 'L'
first is an arrow function: it takes text and gives back text[0].
Step 2: the last character
The last character is at length - 1, so compute that inside the brackets.
const word = 'Lagos';
const last = (text) => text[text.length - 1];
console.log(last(word)); // 's'
word.length is 5, so this reads word[4], which is 's'.
Step 3: the same thing with charAt
charAt is a method, so it takes the index in round brackets.
const word = 'Lagos';
console.log(word.charAt(0)); // 'L'
console.log(word.charAt(4)); // 's'
console.log(word.charAt()); // 'L'
console.log(word[0].length); // 1
console.log(typeof word[0]); // 'string'
So far the two ways agree. charAt() with nothing in the brackets reads index 0. And the last two lines prove what we said earlier: one character is a string of length 1.
Step 4: ask for a character that isn't there
Now ask both for index 99, far past the end of the word.
const word = 'Lagos';
console.log(word[99]); // undefined
console.log(JSON.stringify(word.charAt(99))); // "", an empty string
Here they split. Brackets give undefined, JavaScript's value for "nothing here". charAt gives '', an empty string. JSON.stringify is used only so you can see the empty string: printed on its own, it would just be a blank line.
Step 5: try a negative index
You might hope -1 means "the last character". It doesn't, for either of them.
const word = 'Lagos';
console.log(word[-1]); // undefined
console.log(JSON.stringify(word.charAt(-1))); // "", an empty string
Neither one counts back from the end. Brackets treat -1 as a position that doesn't exist, and charAt treats any position outside the string as "nothing". To count from the end you need at(-1), which is the next exercise.
Why the difference matters
Code often checks the result with if (c). Both undefined and '' count as false there, so that code works either way. Trouble starts when you call a method on the result:
const word = 'Lagos';
console.log(word.charAt(99).toUpperCase()); // '', an empty string
console.log(word[99].toUpperCase()); // TypeError: Cannot read properties of undefined (reading 'toUpperCase')
The charAt version quietly gives an empty string. The bracket version crashes, because undefined has no methods. Neither is wrong, but you need to know which one you have.
The full solution
Here is the complete answer: both ways to read a character, and both out-of-range results side by side. Press Run and look at the two lines under "out of range".
const word = 'Lagos';
const first = (text) => text[0];
const last = (text) => text[text.length - 1];
console.log('first:', first(word), ' last:', last(word));
console.log('--- out of range ---');
console.log('word[99] :', word[99], '<- undefined');
console.log('word.charAt(99):', JSON.stringify(word.charAt(99)), '<- an empty string');
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('brackets give one character', first(word), 'L');
test('charAt gives the same', word.charAt(0), 'L');
test('the last character', last(word), 's');
test('past the end, brackets give undefined', word[99], undefined);
test('but charAt gives an EMPTY STRING', word.charAt(99), '');
test('a negative index with brackets is undefined', word[-1], undefined);
test('and charAt(-1) is empty too, not the last character', word.charAt(-1), '');
test('charAt with no argument reads index 0', word.charAt(), 'L');
test('what comes back is a string of length one', word[0].length, 1);
test('so there is no character type to compare against', typeof word[0], 'string');
The two disagree exactly where it matters. text[99] is undefined; text.charAt(99) is ''. Code that tests the result with if (c) treats both as falsy and gets away with it, but code that does c.toUpperCase() throws on one and not the other.
Neither reads a negative index. That is what at is for, and it is the next exercise.
Common mistakes
- Using
text[-1]for the last character. It givesundefined. Usetext[text.length - 1]ortext.at(-1). - Using
text[text.length]. Indexes start at 0, so this is one past the end. - Calling a method on
text[i]without checking it exists. Past the end it isundefined, andundefined.toUpperCase()throws.
Try it yourself
- Write
initial(name)that returns the first letter of a name in upper case, soinitial('ada')gives'A'. - What does
initial('')do with brackets, and what does it do if you switch tocharAt? Explain the difference. - Write
endsWithS(word)using the last character, and test it with'cats'and'cat'.