Both, the String.prototype.charAt()
method and using the bracket notation can be used to access characters in a string. However, the have the following differences between them:
Browser Support
The String.prototype.charAt()
method is supported by all browsers (new and old). However, the bracket notation syntax to access string characters was introduced in ES5.
Return Value for Out-of-Range Index
If the index you're trying to access is out of range (i.e. does not exist or cannot be found), the String.prototype.charAt()
method would return an empty string, while the bracket notation syntax will return undefined
. For example:
const str = ''; console.log(str[1]); // undefined console.log(str.charAt(1)); // ''
Handling of Non-Numeric Indexes
When you use the bracket notation, the string is treated like an array-like object (where individual characters correspond to a numerical indexes). Therefore, any non-existing index returns undefined
. In the case of the String.prototype.charAt()
method, however, any non-numeric index is coerced to an integer index. This means that all truthy values are coerced to number 1
, and all falsy values are coerced to number 0
. This results in the following:
const str = 'bar'; console.log(str[NaN]); // undefined console.log(str.charAt(NaN)); // 'b' console.log(str[undefined]); // undefined console.log(str.charAt(undefined)); // 'b' console.log(str[false]); // undefined console.log(str.charAt(false)); // 'b' console.log(str[true]); // undefined console.log(str.charAt(true)); // 'a'
One other special case to take note of is using a floating point as an index. For this, the charAt()
method will round the number down. For example:
console.log(str[1.4]); // undefined console.log(str.charAt(1.4)); // 'a' console.log(str[0.9]); // undefined console.log(str.charAt(0.9)); // 'b'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.