Loose (==) vs strict (===) equality in JavaScript
== vs === in JavaScript
JavaScript has two equality operators: loose equality (==) and strict equality (===). Understanding the difference is essential for writing reliable code.
Strict Equality (===)
Compares value AND type. No type coercion is performed.
javascript
5 === 5; // true
5 === "5"; // false (different types)
true === 1; // false
null === undefined; // false
NaN === NaN; // false (NaN is never equal to itself)Loose Equality (==)
Compares values after type coercion. JavaScript converts operands to the same type before comparing.
javascript
5 == "5"; // true (string "5" β number 5)
true == 1; // true (true β 1)
false == 0; // true (false β 0)
null == undefined; // true (special rule)
"" == 0; // true ("" β 0)
"0" == false; // true ("0" β 0, false β 0)Coercion Rules for ==
| Comparison | Coercion | Result |
|---|---|---|
number == string | String β Number | 5 == "5" β true |
boolean == any | Boolean β Number first | true == "1" β true |
null == undefined | Always true | Special rule |
null == 0 | Always false | null only == undefined |
object == primitive | Object β primitive via valueOf/toString |
Object Comparison
Both == and === compare objects by reference, not by value:
javascript
const a = { x: 1 };
const b = { x: 1 };
const c = a;
a === b; // false (different references)
a === c; // true (same reference)
a == b; // false (still by reference)
[] == []; // false
{} == {}; // falseSpecial Cases
javascript
NaN === NaN; // false
NaN == NaN; // false
// Use Number.isNaN() or Object.is() instead
Object.is(NaN, NaN); // true
Object.is(+0, -0); // false (=== gives true)When to Use Which
| Operator | Use When |
|---|---|
=== | Always (default choice) |
== | Only when checking null == undefined |
javascript
// β
Common pattern: check for null OR undefined
if (value == null) {
// value is null or undefined
}
// Same as:
if (value === null || value === undefined) {
// value is null or undefined
}Important:
Always use === by default. The only widely accepted use of == is checking for null/undefined in one comparison: if (value == null). ESLint rule eqeqeq enforces this best practice.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.