Avoiding Common == Pitfalls
You'll learn how == creates unexpected bugs in real code and how === prevents them.
By now you know that == performs type coercion while === doesn't. But theory becomes reality when you see actual pitfalls that trip up developers every day. Let's look at concrete examples where == betrays your expectations.
The "Looks Equal" Trap
// Example 1: The zero family
0 == '' // true — both coerce to 0
0 == '0' // true — string '0' becomes number 0
'' == '0' // false — wait, what?!
// With ===, no surprises:
0 === '' // false
0 === '0' // false
'' === '0' // false
This triangle of confusion happens because == applies different coercion rules depending on the types involved. Your brain expects transitivity (if A == B and B == C, then A == C), but == doesn't guarantee it.
The Falsy Value Mixup
// Example 2: False friends
false == 0 // true
false == '' // true
false == [] // true
null == undefined // true
null == 0 // false — null is special!
// === tells the truth:
false === 0 // false
null === undefined // false
These hidden conversions make debugging nightmares. Imagine checking if (userInput == false) when the user enters "0" or an empty array!
The Defensive Solution
Always default to === and !==. Only use == when you specifically want coercion—and even then, document why.
Key Takeaway: Use === to avoid the unpredictable coercion quirks of ==, especially with zeros, empty strings, booleans, and null/undefined comparisons.