var arr = [];
Boolean(arr) // true
Boolean(!arr) // false
arr == arr // true
arr == !arr // true ??? what ???
I do not want to get the answer that 'recommend using ===
instead of ==
'.
I would like to know the reason for this phenomenon and the principle of type conversion of JavaScript.
The reason for [] == false even though [] is truthy is: the comparison [] == false compares the value of [] to false . And to get the value of [] , the JavaScript engine first calls [].
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; else if either operand is a string, the other operand is converted to a string if possible.
So === faster than == in Javascript === compares if the values and the types are the same. == compares if the values are the same, but it also does type conversions in the comparison. Those type conversions make == slower than ===.
Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!
Type conversion in JS, particularly with regards to loose equality, is a tricky beast.
The best place to always start when answering the question "why does this particular loose equality evaluate this way" is to consult this table of equality comparisons by operand type.
In this case, we can see that for [] == false
, Operand A is an Object and Operand B is a Boolean, so the actual comparison performed is going to be ToPrimitive(A) == ToNumber(B)
.
The right side of that is simple; ToNumber(false)
evaluates to 0
. Done and done.
The left side is more complex; you can check the official ECMAScript spec for full documentation of ToPrimitive
, but all you really need to know is that in this case it boils down to A.valueOf().toString()
, which in the case of the empty array is simply the empty string ""
So, we end up evaluating the equality "" == 0
. A String/Number ==
comparison performs ToNumber
on the string, and ToNumber("")
is 0
, so we get 0 == 0
, which is of course true
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With