Is there any reason I should use string.charAt(x)
instead of the bracket notation string[x]
?
There is a difference when you try to access an index which is out of bounds or not an integer.
string[x]
returns the character at the x
th position in string
if x
is an integer between 0 and string.length-1
, and returns undefined
otherwise.
string.charAt(x)
converts x
to an integer using the process explained here (which basically rounds x
down if x
is a non-integer number and returns 0 if parseInt(x)
is NaN
) and then returns the character at the that position if the integer is between 0 and string.length-1
, and returns an empty string otherwise.
Here are some examples:
"Hello"[313] //undefined
"Hello".charAt(313) //"", 313 is out of bounds
"Hello"[3.14] //undefined
"Hello".charAt(3.14) //'l', rounds 3.14 down to 3
"Hello"[true] //undefined
"Hello".charAt(true) //'e', converts true to the integer 1
"Hello"["World"] //undefined
"Hello".charAt("World") //'H', "World" evaluates to NaN, which gets converted to 0
"Hello"[Infinity] //undefined
"Hello".charAt(Infinity) //"", Infinity is out of bounds
Another difference is that assigning to string[x]
does nothing (which can be confusing) and assigning to string.charAt(x)
is an error (as expected):
var str = "Hello";
str[0] = 'Y';
console.log(str); //Still "Hello", the above assignment did nothing
str.charAt(0) = 'Y'; //Error, invalid left-hand side in assignment
The reason why assigning to string[x]
doesn't work is because Javascript strings are immutable.