DEV Community

The Creative CodeFlow
The Creative CodeFlow

Posted on

JavaScript Has a Weird Trick: [] == false Is True

JavaScript Has a Weird Trick: [] == false Is True
What do you think this prints?
console.log([] == false);
console.log([] === false);

The output is:
true
false

Wait… how can an empty array equal false?
The answer is JavaScript's type coercion.
When you use ==, JavaScript may convert values to different types before comparing them.
In this example:
[] == false

JavaScript converts false to 0, and the empty array to an empty string, which becomes 0 when converted to a number.
So the comparison becomes:
0 == 0 // true

But === checks both value and type without performing this kind of type conversion.
[] === false // false

An array and a boolean are different types.
Here's the lesson: JavaScript sometimes does more work behind the scenes than your code suggests.
For predictable comparisons, prefer === unless you specifically need the conversion behavior of ==.
Try these yourself:
console.log("" == false);
console.log("0" == false);
console.log([] == ![]);

Can you predict all three outputs before running the code?

Top comments (0)