Strict Equality (== vs ===)
TL;DR
===(Strict Equality): Checks if the value AND the type are identical.==(Loose Equality): Attempts to convert the types to match before comparing the values (Type Coercion).
Always use === in modern JavaScript to avoid massive logical bugs.
Mental Model
How It Works
When you use ==, JavaScript follows a complex set of rules called the Abstract Equality Comparison Algorithm.
If the types differ, it tries to convert them to numbers:
"5" == 5-> Converts"5"to5->5 == 5(true)true == 1-> Convertstrueto1->1 == 1(true)[] == false-> Converts[]to"", then to0. Convertsfalseto0->0 == 0(true!)
When you use ===, JavaScript performs the Strict Equality Comparison. If the typeof the two operands is different, it immediately returns false. No conversion happens.
Example
// Loose Equality (==) - Chaos
console.log(1 == "1"); // true
console.log(0 == false); // true
console.log([] == ""); // true
console.log([] == 0); // true
console.log([1,2] == "1,2"); // true! Arrays are coerced to strings.
// Strict Equality (===) - Sanity
console.log(1 === "1"); // false (number vs string)
console.log(0 === false); // false (number vs boolean)
console.log([] === ""); // false (object vs string)
Common Output Question
console.log(null == undefined);
console.log(null === undefined);
console.log(NaN === NaN);
Q: What does this output?
A:
true: The ECMAScript spec specifically hardcodesnullandundefinedto loosely equal each other.false: They are of different types (objectvsundefined).false:NaNis incredibly unique. It is the only value in JavaScript that is not strictly equal to itself. You must useNumber.isNaN()orObject.is(NaN, NaN)to check for it.
Senior Interview Question
Q: Are there any valid use cases for using == in modern JavaScript?
A: The only widely accepted use case for loose equality is checking for the absence of a value.
Writing if (value == null) is a shorthand trick that returns true if value is EITHER null OR undefined, because of how they loosely equate to each other. This saves you from writing if (value === null || value === undefined). Outside of this single pattern, == should be strictly forbidden by linters (like ESLint’s eqeqeq rule).