andrerpena andrerpena - 6 months ago 9
Javascript Question

Why doing a boolean conversion using Boolean is different than an automatic conversion done by ==?

It's not new that JavaScript has a messed up truth table:

truth table

... but I'm trying to understand the rationale. MDN says:

Equality (==)




The equality operator converts the operands if they are not of the
same type, then applies strict comparison. If both operands are
objects, then JavaScript compares internal references which are equal
when operands refer to the same object in memory.


Ok, so... if I'm comparing:

"0" == false // which is true


... I assume the JS engine will try to convert "0" to boolean before comparing it to false (or the other way around). The problem is that
Boolean("0")
is true. So:

Boolean("0") == false
IS NOT EQUAL TO
"0" == false


Why?

Answer

The specification isn't a general "let's do what seems natural" rule, it is made of a sequence of simple rules. Let's apply it, you'll see that your assumption isn't verified:

First step:

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

false is converted to a number and it's 0 (you can check +false in the console).

Second step:

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

"0" is compared to 0, which is done by converting "0" to 0

If you're looking for a global rational of abstract equality among defined values, I'd say it is to prefer numbers, then strings.

As for the second check, Boolean("0") == false, it's simpler: the Boolean function converts to true anything that isn't falsy (0, -0, null, false, NaN, undefined, or "").

Comments