Search code examples
javascriptbooleantype-conversionequals-operator

Why 1.2 == true returns false if Boolean(1.2) is actually true?


Brushing up on == and ===, I can't really convince myself with an explanation about this.

I take a floating point number and do a == with a Boolean true. It returns false. But when I explicitely convert the floating point number to a Boolean, it returns true. Shouldn't the == actually first convert the 1.2 to a Boolean and than compare it to the true on the other side?

> Boolean(1.2)
true
> 1.2 == true
false

On the other hand, an "integer" will behave as I expect it.

> 1 == true
true

Solution

  • As you stated above 1.2 will not be converted into boolean first.

    According the the abstract equality comparison algorithm, the following steps will be performed

    • 1.2 == true
    • 1.2 == toNumber(true) (In algorithm, step no 7)
    • 1.2 == 1 (In algorithm, step no 1)
    • false