Should I use == or === in JavaScript?

HTML, CSS & JS 2 min read
Short answer

Use ===, which compares without type coercion. == converts types first and produces results almost nobody predicts correctly.

javascript
0 == '';           // true
0 == '0';          // true
'' == '0';         // false   <-- not even transitive
null == undefined; // true
[] == false;       // true
[] == ![];         // true
NaN == NaN;        // false

Those rules are memorisable but not worth memorising. === sidesteps all of it:

javascript
0 === '';          // false
null === undefined // false

#The one exception

javascript
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:

javascript
{ a: 1 } === { a: 1 }    // false — different objects

For 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.