2

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.

atish shimpi
  • 4,873
  • 2
  • 32
  • 50
yaromir
  • 378
  • 7
  • 17

1 Answers1

4

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. :)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • As well as "Some differences should be noted between the syntax of a StringNumericLiteral and a NumericLiteral (see 7.8.3): ... A StringNumericLiteral that is empty or contains only white space is converted to +0." – Jon Skeet Nov 24 '14 at 16:41
  • I wonder why they bothered with two productions in the main _StringNumericLiteral_ entry. They could have just added _opt_ after _StrNumericLiteral_. – Barmar Nov 24 '14 at 16:45
  • @LightnessRacesinOrbit: Unless I'm misunderstanding you, the *StrWhiteSpace(opt) StrNumericLiteral StrWhiteSpace(opt)* allows for consecutive white space. – six fingered man Nov 24 '14 at 16:49
  • Yes it does, because _StrWhiteSpace_ can be multiple whitespace characters. – Barmar Nov 24 '14 at 16:49
  • @Barmar: Oh yes, so it can! Then, yeah, I don't see why either. Perhaps they figured it makes the individual "use cases" clearer. – Lightness Races in Orbit Nov 24 '14 at 16:50
  • @Barmar: I would think the *HexIntegerLiteral* needs to be excluded when referencing the string numeric literal elsewhere in the spec. – six fingered man Nov 24 '14 at 16:52
  • Oh, indeed. OK, so i need to be more attentive. :) Thanks. But why didn't they add `StringNumericLiteral ::: [empty]` to the grammar description? Something like `StringNumericLiteral ::: [empty] | StrWhiteSpaceopt | StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt`? – yaromir Nov 24 '14 at 16:53
  • @yaromir: They didn't need to. Those "opt" mean the whitespace is _optional_, so the grammar already allows for the empty production. – Lightness Races in Orbit Nov 24 '14 at 16:54