string.charAt(i) vs string[i]
Written byPhuoc Nguyen
Created
10 Jun, 2020
Category
JavaScript
There are two ways to access an individual character of a string:
- using the
`charAt[index]`
method - and using bracket notation such as
`'hello'[1]`
In both ways,
`'hello'[1]`
and `'hello'.charAt(1)`
returns the second character `e`
.#Differences
-
The second way is standard of ECMA 5, and is supported in modern browsers. It is not supported in the very old browsers such as IE 6, 7. (I don't think we still need to support these versions of IE).
-
Here is a table listing the expect result of both methods:
Method `index`
is in the range of 0 and`string.length - 1`
Other cases `string.charAt(index)`
character at associate position an empty string `string[index]`
character at associate position `undefined`
We will get different results in some edge cases if you don't pass a proper index (not an integer or out of bounds).js'hello'[NaN]; // undefined'hello'.charAt(NaN); // 'h''hello'[undefined]; // undefined'hello'.charAt(undefined); // 'h''hello'[true]; // undefined'hello'.charAt(true); // 'e''hello'['00']; // undefined// return 'h' because it will try to convert `00` to number first'hello'.charAt('00');'hello'[1.5]; // undefined// return 'e' because it will round 1.23 to the number 1'hello'.charAt(1.23);In the case the index is out of bounds:js'hello'[100]; // undefined'hello'.charAt(100); // ''
#Good to know
Why does
`'hello'.charAt(true)`
return `e`
?The
`charAt(index)`
method will try to convert the index to the number first. Since `Number(true) === 1`
, `charAt(true)`
will returns the character at the one index position, i.e, the second character.Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn