[] == false // true
[] == ![] // true
Wait… what? 🤯
How can an empty array be equal to false?
Let’s break it down
JavaScript’s == operator performs type coercion.
That means it tries to convert values to the same type before comparing them.
Step 1
[] == false
-
falsebecomes0 -
[]becomes""(empty string) -
""becomes0
So we end up with:
0 == 0 // true
Step 2
[] == ![]
First evaluate ![]:
-
[]is truthy -
![]becomesfalse
So now we have:
[] == false
Which we already know is:
true
Why this matters
The == operator can lead to unexpected results because of implicit type conversion.
That’s why most developers prefer:
===
It compares values without coercion.
Takeaway
JavaScript doesn’t behave randomly.
It follows rules — even strange ones.
Understand coercion, and the weirdness disappears.
Happy coding ✨
Top comments (0)