I am doing some exercises in my object-oriented javascript book, I notice that this:
var a = "hello";
a.charAt('e'); // 'h'
a.charAt('adfadf'); //'h'
Why is the string in the argument seemingly evaluated to the integer 0 for the charAt() method for strings?
Edit: I was aware that the charAt()’s usage usually takes an integer, and the exercise feeds charAt() with a string, and I also was aware that the string is likely then to be coerced into an integer first, which I did verify to be NaN. Thanks Kendall, for suggesting putting this missing bit of information in the question proper
Thanks!
Because
Number('e')isNaN, and<any nonempty string>.charAt(NaN)just returns the first character. This behavior is exactly what is laid out in the spec:Step 3 is the crux of the matter.
ToIntegerof both'e'and'adfadf'is0. Why? Again, time to hit the spec:We need to go deeper! What is ToNumber(‘e’), and what is ToNumber(‘adfadf’)? If you’re surprised that I’m once again about to quote the spec, I’m doing something wrong:
…I’m not going to quote the entire grammar for StringNumericLiteral. Because
'e'and'adfadf'are neither StrDecimalLiteral s nor HexIntegerLiteral s, ToNumber of both of those values is NaN. Finally we have the conversion: from string toNaNto0, which brings us back up the chain tocharAt: position is0, socharAt('e')andcharAt('adfadf')both return the leftmost character in S.Now, if those strings were instead valid StrNumericLiteral s, such as
'0xe'and'0xadfadf':well, that’s a different story for a different answer.