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

Asked

Viewed 3,647 times

4

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

Why would you behave?

Example:

console.log(Boolean('0'));
console.log(Boolean(0));

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


console.log(Boolean('1'));
console.log(Boolean(1));

If I convert '0' for Boolean is true, but I compare myself to false is true? What’s the reason in that?

Don’t try to understand, just accept it! It shows you trust the language :D

1 answer

7


The reason the behavior is different has to do with which type conversions to be made.

When you have Boolean('0') is the same as Boolean('x') for in the eyes of Boolean-like is a string with content. In this case the one responsible for the conversion is the Boolean().

When you have a comparator == then the rules are different. You can read on MDN the following:

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 into numbers before a comparator where one of the members of the comparison is a boolean.

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

One can read about the logic of comparison also directly on specification of Ecmasrcript here, and in this case (in the second example) falls first in the case 7, and then in case 5.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.