You should use === (strict equality) by default for almost all comparisons in JavaScript because it checks both value and type without hidden type coercion. == (loose equality) converts mismatched types automatically before comparing, which can produce surprising results—though some developers intentionally use x == null as a shorthand to check for both null and undefined at once.
1. Strict Equality (===) vs. Loose Equality (==)
=== returns true only when operands share the same type and value, whereas == runs abstract coercion rules when types differ:
// Comparing strict equality (===) and loose equality (==)
console.log(5 === "5"); // false (number vs. string)
console.log(5 == "5"); // true ("5" coerces to number 5)
console.log(false === 0); // false (boolean vs. number)
console.log(false == 0); // true (false coerces to 0)
console.log(null === undefined); // false (different types)
console.log(null == undefined); // true (special rule in JS spec)
- Predictable type safety:
===prevents strings like"0"or""from silently matching numbers or booleans. - No non-transitivity surprises: Loose equality is not transitive (for example,
"0" == 0and0 == "", yet"0" != ""), making logic harder to reason about. - Object identity still matters: Both
===and==compare object/array/function references by identity rather than deep contents.
2. The One Common == Idiom: Checking null or undefined
If you want to guard against both null and undefined in one expression, value == null is a well-known exception where loose equality behaves cleanly:
// Idiomatic null/undefined check vs. explicit checks
function isMissing(value) {
return value == null; // true for both null and undefined, false for 0, "", or false
}
console.log(isMissing(null)); // true
console.log(isMissing(undefined)); // true
console.log(isMissing(0)); // false
console.log(isMissing("")); // false
- Explicit alternative: Writing
value === null || value === undefined(or optional chaining/nullish coalescing??) states the intent unambiguously for any reader. - Keep
===everywhere else: Use===and!==for numbers, strings, booleans, enums/status constants, and DOM/API values.
3. Common Traps to Avoid
Relying on implicit coercion or misunderstanding === edge cases often leads to subtle bugs:
- Assuming
===catchesNaN:NaN === NaNevaluates tofalsein JavaScript; useNumber.isNaN(value)to test forNaN. - Treating
==as “deep equality”: Neither===nor==compares two arrays or plain objects by their properties ([1, 2] == [1, 2]isfalse). - Mixing numeric strings with numbers from inputs or APIs: Always convert form/query values explicitly (such as
Number(input.value)) before comparing with===.
TL;DR: Always default to === (and !==) to avoid unexpected type coercion bugs, reserving value == null at most when intentionally checking for both null and undefined.
Want to test a few tricky == vs. === examples, or move on to the next JavaScript topic?
