steveyang
steveyang

Reputation: 9298

How the string.charAt() works when passing in a string as argument?

According to the MDN JS Doc, the charAt method takes in an integer and returns an the character at the index. And

If the index you supply is out of range, JavaScript returns an empty string.

What I found is that it also takes string as an argument and the return value is intriguing.

The example code: http://jsfiddle.net/yangchenyun/4m3ZW/

var s = 'hey, have fun here.'
>>undefined
s.charAt(2);
>>"y" //works correct
s.charAt('2');
>>"y" //This works too
s.charAt('a');
>>"h" //This is intriguing

Does anyone have a clue how this happens?

Upvotes: 3

Views: 1213

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

The algorithm is described in Section 15.5.4.4 in the specification. There you will see (pos being the parameter passed to charAt):

(...)
3. Let position be ToInteger(pos).
(...)

ToInteger is described in Section 9.4:

  1. Let number be the result of calling ToNumber on the input argument.
  2. If number is NaN, return +0.
    (...)

'a' is not a numerical string and hence cannot be converted to a number, so ToNumber will return NaN (see Section 9.3.1) which then results in 0.

On the other side, if you pass a valid numerical string, such as '2', ToNumber will convert it to the corresponding number, 2.


Bottom line:

s.charAt('a') is the same as s.charAt(0), because 'a' cannot be converted to an integer.

Upvotes: 9

Related Questions