Why javascript treats 0 equal to empty string? [duplicate]

Quoting the doc (MDN):

Equal (==)

If the two operands are not of the same type, JavaScript converts the
operands then applies strict comparison. If either operand is a number
or a boolean, the operands are converted to numbers if possible; else
if either operand is a string, the other operand is converted to a
string if possible.

As a operand type here is Number, b gets converted to Number as well. And Number('') evaluates to 0.

This can be quite surprising sometimes. Consider this, for example:

console.log(0 == '0');  // true
console.log(0 == '');   // true
console.log('' == '0'); // O'RLY?

… or this:

console.log(false == undefined); // false
console.log(false == null);      // false
console.log(null == undefined);  // fal.... NO WAIT!

…and that’s exactly why it’s almost always recommended to use === (strict equality) operator instead.

Leave a Comment