35

Why is 0 == "" true in JavaScript? I have found a similar post here, but why is a number 0 similar an empty string? Of course, 0 === "" is false.

Community
  • 1
  • 1
Horst Walter
  • 13,663
  • 32
  • 126
  • 228

1 Answers1

74
0 == ''

The left operand is of the type Number.
The right operand is of the type String.

In this case, the right operand is coerced to the type Number:

0 == Number('')

which results in

0 == 0

From the Abstract Equality Comparison Algorithm (number 4):

If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

Source: http://es5.github.com/#x11.9.3

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • Thanks, I did just expect it the other way round, the 0 converted to string and then false. – Horst Walter Sep 30 '11 at 01:20
  • Yes, on the other hand this means that saying both are falsy - as in the other answers, is not quite correct. Because - as you very well showed - the reason is that "" => 0. Thanks for your support! – Horst Walter Sep 30 '11 at 01:26
  • 1
    @Horst - yes, that's right. Both _are_ falsy, as you can see if you use them alone in `if (0)` or `if("")`, but in the case of an `==` comparison that's not what's happening. (Not sure why Šime also left a comment above saying "Because both value are falsy".) – nnnnnn Sep 30 '11 at 01:29
  • 3
    Ooh, I didn't know about es5.github.com. Much handier than typing out page numbers into the PDF. – millimoose Sep 30 '11 at 01:32
  • @nnnnnn That was my first reaction. It turned out to be incorrect. – Šime Vidas Sep 30 '11 at 01:47
  • Which sometimes makes me hate Javascript's conversion system. In a language like R, it is 0 which would be converted to character "0" and the result would be, as expected, false. Converting 0 to "0" does have some logic, but converting "" to 0 doesn't have any logic at all... – Adrian Jan 01 '17 at 14:34