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

3

Why 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 Boolean('0') to true is Boolean(0) , but if I compare with '0' is it true? What is the reason for this?

Do not try to understand, just accept! This shows that you trust the language: D

    
asked by anonymous 21.09.2016 / 20:41

1 answer

6

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

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

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

  

Equal (==)

     

If the two operands are 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 in numeral to a comparator where one of the comparison members is a Boolean.

So the comparison is between Number('0') and Number(false) which are two 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 in the 7 case, and then in the 5 case.

  

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

    
21.09.2016 / 20:49