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.

9
  • You mean 0 is "casted" in false, "" is casted in false and the check is false == false => true Commented Sep 30, 2011 at 1:12
  • For PHP, see php.net/manual/en/types.comparisons.php
    – apscience
    Commented Sep 30, 2011 at 1:13
  • I believe it's because Javascript automagically coerces strings and numbers in some contexts, the == operator is one of those contexts, and "" coerces to 0.
    – millimoose
    Commented Sep 30, 2011 at 1:14
  • 2
    @HorstWalter No. The sting is coerced to the Number type. See my answer. Commented Sep 30, 2011 at 1:15
  • 1
    @Ӫ_._Ӫ Yea, I had the idea that a == comparison of two falsy values always evaluates to true. But then I remembered NaN != NaN... and that whole idea collapsed lol. Commented Sep 30, 2011 at 1:42

1 Answer 1

74
+500
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

6
  • 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) 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
    Commented Sep 30, 2011 at 1:29
  • 3
    Ooh, I didn't know about es5.github.com. Much handier than typing out page numbers into the PDF.
    – millimoose
    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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.