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.
Related: Why 1 == true is "true" and 2 == true is "false"?
– rray
@rray thanks. I couldn’t find her. It seems that characters like
=
and related make difficult the location of questions, hehehe– Wallace Maxters