Why [] == ![] in JavaScript: Understanding Loose Equality and Its Pitfalls
This article explains the surprising result of the JavaScript expression [] == ![], detailing how empty arrays are truthy, how they are coerced to strings and numbers during loose equality comparison, and why using strict equality (===) or TypeScript avoids such confusing behavior.
This article examines the puzzling JavaScript expression [] == ![] and explains why it evaluates to true despite seeming illogical.
What Happens Internally
In JavaScript an empty array [] is a truthy value, so applying the logical NOT operator yields false . During loose equality comparison the engine then coerces both sides to primitive values: [] becomes an empty string "" , which is further converted to the number 0 , while false also becomes 0 . Since 0 == 0 , the original expression evaluates to true .
Because the empty array is truthy, ![] is false . The comparison then proceeds as [] == false , which follows the same coercion steps described above.
Why [] == [] Is False
When two arrays are compared with == (or === ) JavaScript does not compare their contents; it compares references. Two distinct array objects never share the same reference, so the result is always false .
How to Compare Arrays Properly
If the arrays are sorted, you can compare their JSON string representations:
JSON.stringify(arr1) === JSON.stringify(arr2)
For unsorted arrays a more generic approach is to compare lengths and then check each element with every() :
arr1.length === arr2.length && arr1.every((v,i)=> v===arr2[i])
Final Thoughts
The loose equality operator == can produce results that make no sense in real‑world logic, such as [] == ![] . The safest practice is to always use strict equality === , adopt TypeScript for stronger type checking, and rely on modern language features to avoid these pitfalls.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.