JavaScript's loose equality (==) can produce some surprising results because of type coercion. Here's a classic interview question that confuses even experienced developers.
If you think you know JavaScript, try answering this without running the code.
console.log([] == ![]);
🤔 What will be the output?
A. true
B. false
C. undefined
D. TypeError
Take a moment to guess before reading further.
✅ Answer
The output is:
true
Surprised?
Let's break it down step by step.
Step 1: Evaluate ![]
In JavaScript, every object (including an empty array) is truthy.
Boolean([]); // true
Therefore,
![] // false
Now the expression becomes:
[] == false
Step 2: Loose Equality (==)
The == operator performs type coercion.
Since one side is a boolean, JavaScript converts it to a number.
false // becomes 0
Now the comparison is:
[] == 0
Step 3: Convert the Array
When an array is compared with a primitive, JavaScript converts the array into a primitive value.
[].toString(); // ""
So the comparison becomes:
"" == 0
Step 4: Convert the String to a Number
An empty string converts to the number 0.
Number(""); // 0
Now JavaScript compares:
0 == 0
Which evaluates to:
true
🔄 Conversion Chain
[] == ![]
↓
![] → false
↓
[] == false
↓
false → 0
↓
[] == 0
↓
[] → ""
↓
"" → 0
↓
0 == 0
↓
true ✅
💡 Why Does This Happen?
The == operator follows JavaScript's Abstract Equality Comparison rules.
Instead of comparing values directly, JavaScript automatically converts operands into compatible types before making the comparison.
That's why many developers recommend using:
===
The strict equality operator (===) compares both value and type, avoiding unexpected type coercion.
âš¡ Key Takeaways
[] is an object, and all objects are truthy.
![] evaluates to false.
false is converted to 0.
[] becomes an empty string ("").
"" converts to 0.
Finally, JavaScript compares 0 == 0, which is true.
🧩 Your Turn
Without running the code, what do you think this prints?
console.log([] + []);
Drop your answer in the comments before testing it.
If you enjoyed this puzzle, follow me for more JavaScript interview questions, tricky outputs, and deep dives into how JavaScript actually works.
Happy Coding! 🚀
Top comments (0)