JavaScript has two equality operators that look similar but behave differently. Most confusion comes from not knowing when the language will convert types for you.
The Two Operators
===(Strict Equality) → compares value + type, no type conversion.==(Loose Equality) → compares value after type coercion, which makes it weird but sometimes useful.
Common Myths (and the truth)
Myth 1: == is always bad, never use it.
Wrong.
Truth: == can be useful if you intentionally want coercion, e.g.
0 == false; // true
'' == false; // true
null == undefined; // trueIt’s dangerous when you don’t expect coercion, but not always “bad”.
Myth 2: === is always safer.
Not always.
Truth: === avoids surprises, but sometimes you want coercion:
if (input == null) {
// catches both null and undefined
}Here, == is shorter and clearer than writing:
if (input === null || input === undefined) { ... }Myth 3: null and undefined are equal to everything with ==.
Nope.
Truth: they’re only loosely equal to each other:
null == undefined; // true
null == 0; // false
undefined == false; // falseMyth 4: NaN == NaN is true.
Nope.
Truth: NaN is never equal to anything, not even itself:
NaN == NaN; // false
NaN === NaN; // falseYou must use:
Number.isNaN(NaN); // trueMyth 5: Objects are compared by value.
Nope.
Truth: Objects are compared by reference, always:
{} == {} // false
[] == [] // falseEven if they look identical, different references → not equal.
Myth 6: [] == 0 is false.
Weirdly, it’s true.
Truth: because coercion happens:
[] == 0;
// [] → "" → 0
// so 0 == 0 → trueMyth 7: "0" == false is false.
Actually true.
Truth: "0" → number 0, and false → number 0, so:
'0' == false; // trueRule of Thumb
- Use
===by default for safety. - Use
==only when you know coercion rules and want them (esp. fornull == undefined). - Always beware of weird corner cases like
[] == ![].
