What is the difference between == and === in JavaScript?
=== (strict equality) compares value and type with no conversion. == (loose equality) converts both sides to a common type first, then compares.
=== — true only when type and value both match. Predictable and preferred.
== — applies coercion, so "5" == 5 and null == undefined are both true.
Best practice: always use === unless you deliberately want loose matching. It avoids surprising coercion bugs.
// === (strict) — predictable
console.log(1 === 1); // true
console.log(1 === '1'); // false (different types)
console.log(null === undefined); // false
// == (loose) — type coercion surprises
console.log(1 == '1'); // true (string coerced to number)
console.log('' == 0); // true (both coerce to 0)
console.log(null == undefined); // true (special rule)
console.log([] == false); // true ([] -> '' -> 0 == 0)
console.log([] == ![]); // true! ([] -> 0, ![] -> false -> 0)
// The one useful == case
function process(value) {
if (value == null) { // Catches both null and undefined
return 'No value';
}
// Equivalent to:
// if (value === null || value === undefined)
}
// NaN is not equal to anything, including itself
console.log(NaN === NaN); // false!
console.log(Number.isNaN(NaN)); // true (correct way to check)=== checks type first — '1' is string, 1 is number, so false immediately. == coerces '1' to 1, then compares. The [] == ![] example is the most mind-bending: [] coerces to 0 via '' -> 0, ![] is false -> 0, so 0 == 0 is true.
NaN !== NaN is another gotcha — use Number.isNaN().
Always use ===. Know the coercion surprises: '' == 0, null == undefined, [] == false.
The value == null shorthand for null/undefined is the one acceptable == use. NaN !== NaN is a bonus gotcha.