If Boolean('0') is true and Boolean(0) is false, why is '0' == false true in Javascript?


Why in javascript Boolean('0') is true , Boolean(0) is false, when comparing '0' (a single zero in the string) with false it returns true ?

Why this behavior?



console.log('0' == false);


If I convert '0' to Boolean is it true , but if I compare it to false is it true? What is the reason for this?

Don't try to understand, just accept! It shows you trust the language 😀


The reason the behavior is different has to do with what type conversions to do.

When you have Boolean('0') is the same as Boolean('x') because in the eyes of the Boolean Type it is a string with content. In other words, in this case, the person responsible for the conversion is Boolean() .

When you have a comparator == then the rules are different. You can read the following on 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;

That is, JavaScript converts both values ​​to number before a comparator where one of the comparison members is a Boolean.

So the comparison is between Number('0') and Number(false) which are both 0 .

You can read about the comparison logic also directly in the ECMASrcript specification here , and in this case (in the second example) it falls first into case 7 , and then into case 5 .

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

Scroll to Top