Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is [] == ![] true in JavaScript? [duplicate]

Tags:

javascript

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.

like image 583
msm082919 Avatar asked Jul 27 '18 00:07

msm082919


People also ask

Why is [] == [] false in 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 [].

Why True == true is false in JS?

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.

Which is faster == or === JavaScript?

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 ===.

Does === return false?

Note that === never causes type coercion, but checks for correct types first and yields false if they are not equal!


1 Answers

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.

like image 154
Hamms Avatar answered Oct 08 '22 19:10

Hamms