JavaScript – Why [] == ![] Evaluates to True

arrayscomparejavascript

I would like to know why the expression given in the title

[] == ![]

is evaluated to true.

You cannot compare arrays as strings. I get that. If

[] == []

will evaluate to false because the references are different. Though if we have the following statement.

var arr = []; 
arr == arr // this evaluates to true simply because references are the same.

In order A == B to return true either A and B have to be false or true.
A == !B in order to return true A can be true and B can be false or vice versa but in this case, A and B are the same values so I don't get it.

Best Answer

Basically Javascript tries to convert both the sides into Number if both the types are not same. And if its an Object, It tries to convert into primitive value

So in this case step by step will be

=> []==![]

=> []==false // Type conversion by the statement itself

=> []==0 // To number of right operand

=> ""==0 // To Primitive call for Array which will in this case convert to empty string

=> 0==0 // To number call of "" which is 0

=> true

One can check for the ecmascript explanation here in the compiler description http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

Related Question