== vs === in JavaScript
āļø Compare == and === in JavaScript
JavaScript has two equality operators, loose equality (==) and strict equality (===). This guide explains the differences between them and how to use them correctly.
ā
Loose equality (==)
ā
Strict equality (===)
ā
Common coercion surprises
ā
Object identity
ā
Comparing NaN
ā
Best practices
#javascript #equality #strictequality #looseequality #typecoercion #comparison #webdev
Comparing == and ===
| Operator | Name | Compares types | Converts types | When to use |
|---|---|---|---|---|
== | Loose equality | No | Yes | Rarely, when intentional coercion is desired |
=== | Strict equality | Yes | No | Preferred default |
Loose equality (==)
== converts operands to a common type before comparing.
This can produce surprising results.
0 == "0"; // true (string converted to number)
"" == 0; // true (empty string converted to 0)
null == undefined; // true
"1" == true; // true (both convert to 1)Strict equality (===)
=== compares both value and type.
No type conversion happens, so the results are predictable.
0 === "0"; // false (different types)
"" === 0; // false
null === undefined; // false
"1" === true; // false=== is recommended for equality checks because == sees all of these as equal:
[] == ""; // true
[] == 0; // true
"" == 0; // true
false == "0"; // trueObject identity
Objects, arrays, and functions are compared by reference, not by contents.
Two objects with the same contents are not strictly equal.
const a = {};
const b = {};
a === b; // false (different references)
const c = a;
a === c; // true (same reference)
[1, 2, 3] === [1, 2, 3]; // falseComparing NaN
NaN is the only value that is not equal to itself, even with strict equality.
NaN === NaN; // false
NaN == NaN; // falseInstead, use Number.isNaN() to check for NaN:
Number.isNaN(NaN); // true
Number.isNaN("not a number"); // falseFull-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.