Should I use == or === in JavaScript?
Use ===, which compares without type coercion. == converts types first and produces results almost nobody predicts correctly.
0 == ''; // true
0 == '0'; // true
'' == '0'; // false <-- not even transitive
null == undefined; // true
[] == false; // true
[] == ![]; // true
NaN == NaN; // falseThose rules are memorisable but not worth memorising. === sidesteps all of it:
0 === ''; // false
null === undefined // false#The one exception
if (value == null) { }This is true for both null and undefined and nothing else. It is a recognised idiom for "no value of either kind", and it is shorter than value === null || value === undefined.
Some teams still ban it for consistency. Either position is defensible; picking one and applying it uniformly is what matters.
#Comparing objects
Both operators compare objects by reference:
{ a: 1 } === { a: 1 } // false — different objectsFor value comparison, compare the fields you care about, or use a deep-equal helper. JSON.stringify(a) === JSON.stringify(b) works for simple data but depends on key order and breaks on undefined, functions and Date.
#NaN
NaN is the only value not equal to itself. Use Number.isNaN(x) — not the global isNaN, which coerces first and calls isNaN('hello') true.
#Object.is
Object.is(a, b) is === with two corrections: NaN equals itself, and +0 does not equal -0. Rarely needed, occasionally exactly right.