How JavaScript's (0 == "") === true agrees with ECMA-262 type conversion rules?

160 Views Asked by At

I've already seen several questions explaining why 0 == "" is true in JavaScript, but i have a bit deeper question.

So the answer to why is 0 == "" is true in JavaScript is that string "" gets converted to number, zero-length string is converted to zero number, but how this agrees with [9.3.1 paragraph of ECMA-262](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3.1) which says that string should be parsed using given formal grammar and if it fails, then such string is converted to NaN. When i looked on this spec i thought that "" is not a string numeric literal and it should be parsed as NaN and NaN is not equal to 0.0.

So why above speculation isn't correct and 0 == "" is actually true?

Thanks in advance.

1

There are 1 best solutions below

8
On BEST ANSWER

The grammar allows for StringNumericLiteral to be empty:

StringNumericLiteral :::
    StrWhiteSpaceopt
    StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt

A few lines down, it says:

A StringNumericLiteral that is empty or contains only white space is converted to +0.

and:

The MV of StringNumericLiteral ::: [empty] is 0.

So I'm afraid you simply didn't fully read the standard passage you're looking at. :)