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.

IT Services Circle
IT Services Circle
IT Services Circle
Why [] == ![] in JavaScript: Understanding Loose Equality and Its Pitfalls

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TypeScriptJavaScriptprogrammingArraysLoose EqualityStrict Equality
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.