Reading — step 1 of 7
Learn
JavaScript's loose equality (==) coerces types — and the rules are infamous. Strict equality (===) does not. Always use === unless you have a deliberate reason for the looser one. This lesson explains why.
Strict equality (===) — the safe default
No type coercion. Same type AND same value:
Loose equality (==) — coerces
With type coercion:
The full rules are a maze. Don't memorize them — just use ===.
Special case: null == undefined
The ONE exception where loose equality is widely used:
Shorter than x === null || x === undefined. Some teams allow this; others enforce strict equality everywhere.
Type coercion: the bigger picture
Loose equality is one place coercion happens. Others:
The + operator:
Comparison operators (<, >, <=, >=) — coerce to numbers (or strings if both are strings):
Boolean contexts (if, &&, ||, !):
The falsy values: false, 0 (and -0), '', null, undefined, NaN. Everything else is truthy.
Object.is — even stricter than ===
Useful when you specifically need NaN === NaN behavior (e.g., comparing values stored in a Map).
Common mistakes
- Using == instead of === —
0 == ''is true; almost never what you want. - Forgetting empty arrays/objects are truthy —
if (arr)doesn't check emptiness; checkarr.length. - Coercion in + with mixed types —
'1' + 2 === '12'but'1' - 2 === -1. + is overloaded; - always coerces to number. - Comparing NaN with === — always false. Use
Number.isNaN(x). - Implicit coercion in if —
if (count != null && count > 0)is the safer guard thanif (count). - Loose null check:
x == nullis the rare legitimate use of==. Some style guides ban even this.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…