DEV Community

FADHILI Josue
FADHILI Josue

Posted on

Unveiling JavaScript Tricks:[] is equal ![]?

[] is equal ![]

Array is equal not array:

[] == ![]; // -> true 
Enter fullscreen mode Exit fullscreen mode

💡 Explanation:

The abstract equality operator converts both sides to numbers to compare them, and both sides become the number 0 for different reasons. Arrays are truthy, so on the right, the opposite of a truthy value is false, which is then coerced to 0. On the left, however, an empty array is coerced to a number without becoming a boolean first, and empty arrays are coerced to 0, despite being truthy.

Here is how this expression simplifies:

+[] == +![]; 0 == +false; 0 == 0; true; 
Enter fullscreen mode Exit fullscreen mode

See also [] is truthy, but not true.

true is not equal ![], but not equal [] too

Array is not equal true, but not Array is not equal true too;
Array is equal false, not Array is equal false too:

true == []; // -> false true == ![]; // -> false false == []; // -> true false == ![]; // -> true 
Enter fullscreen mode Exit fullscreen mode

💡 Explanation:

true == []; // -> false true == ![]; // -> false // According to the specification true == []; // -> false toNumber(true); // -> 1 toNumber([]); // -> 0 1 == 0; // -> false true == ![]; // -> false ![]; // -> false true == false; // -> false 
Enter fullscreen mode Exit fullscreen mode
false == []; // -> true false == ![]; // -> true // According to the specification false == []; // -> true toNumber(false); // -> 0 toNumber([]); // -> 0 0 == 0; // -> true false == ![]; // -> true ![]; // -> false false == false; // -> true 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)