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.
1 Answer
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
-
Thanks, I did just expect it the other way round, the 0 converted to string and then false. Commented Sep 30, 2011 at 1: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! Commented Sep 30, 2011 at 1:26
-
1@Horst - yes, that's right. Both are falsy, as you can see if you use them alone in
if (0)
orif("")
, 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".)– nnnnnnCommented Sep 30, 2011 at 1:29 -
3Ooh, I didn't know about es5.github.com. Much handier than typing out page numbers into the PDF. Commented Sep 30, 2011 at 1:32
-
@nnnnnn That was my first reaction. It turned out to be incorrect. Commented Sep 30, 2011 at 1:47
==
comparison of two falsy values always evaluates to true. But then I rememberedNaN != NaN
... and that whole idea collapsed lol.