JavaScript’s Weirdest Comparison
Source: Dev.to
Why [] == false is true
[] == false // true
The == operator performs type coercion:
falseis converted to0.[]is first converted to an empty string"".- The empty string
""is then converted to0.
Thus the comparison becomes:
0 == 0 // true
Why [] == ![] is true
[] == ![] // true
Evaluation steps:
![]– an empty array is truthy, so applying!yieldsfalse.- The expression now is
[] == false, which we already know evaluates totrue(see above).
Takeaway
The == operator can produce surprising results because of implicit type conversion.
Most developers prefer the strict equality operator ===, which does not perform coercion and therefore avoids these pitfalls.
[] === false // false
[] === ![] // false
Understanding how coercion works removes the “weirdness” from JavaScript comparisons. Happy coding! ✨