Common Equality Pitfalls
You'll learn the sneaky edge cases that trip up even experienced developers when comparing values with == and ===.
The Danger Zone
JavaScript's equality operators hide some surprising behaviors, especially when == performs type coercion. Understanding these pitfalls helps you avoid confusing bugs.
null and undefined: The Special Pair
When using ==, null and undefined are considered equal to each other but not to anything else:
null == undefined // true
null === undefined // false (different types!)
null == 0 // false
undefined == 0 // false
Think of null and undefined as two siblings who only recognize each other with ==, but are strangers to everyone else.
Empty Strings and Falsy Confusion
Empty strings coerce to 0 when compared with numbers using ==:
'' == 0 // true (empty string coerced to 0)
'' === 0 // false (different types)
'0' == 0 // true (string '0' coerced to number)
'0' === 0 // false
The Boolean Trap
Comparing anything to true or false with == triggers unexpected coercion:
'1' == true // true (both coerce to 1)
'0' == false // true (both coerce to 0)
'hello' == true // false (string coerces to NaN, not 1)
The Safe Default
Use === unless you specifically need null == undefined behavior. With ===, what you see is what you get—no hidden conversions.
Key Takeaway: Always prefer === to avoid coercion surprises; the only common exception is checking value == null to catch both null and undefined in one comparison.