charAt[index]
method'hello'[1]
'hello'[1]
and 'hello'.charAt(1)
returns the second character e
.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 |
'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);
'hello'[100]; // undefined'hello'.charAt(100); // ''
'hello'.charAt(true)
return e
?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.