Fundamentalsbeginner
Type Coercion and Equality
How JavaScript automatically converts values between types, and why == and === behave differently.
Type coercion is JavaScript's habit of converting values from one type to another automatically when an operator or comparison expects a different type, and it is responsible for both a lot of convenient code and a lot of infamous bugs. Interviewers love this topic because a handful of quirky one-liners can reveal whether you actually understand the coercion rules or have just memorized outputs.
It's like comparing a printed price tag ('$5') to a coin in your hand (5) — loose equality translates one into the other's 'currency' before comparing, while strict equality just says they're different formats and refuses to compare them at all.
Key Concepts
1
The loose equality operator == performs type coercion before comparing: if the operands are different types, JavaScript converts one or both to a common type using rules defined in the spec (numbers get converted to strings compared as numbers, booleans get converted to numbers, and so on). This is why '5' == 5 is true and, more surprisingly, why null == undefined is true while null === undefined is false. The strict equality operator === skips coercion entirely — if the types differ, it immediately returns false, which makes it far more predictable.
=='5' == 5truenull == undefinednull === undefined
2
Coercion also happens implicitly in other contexts: the + operator coerces to a string if either operand is a string (1 + '1' === '11'), while -, *, and / coerce operands to numbers ('5' - 1 === 4). Truthy/falsy evaluation in if statements and logical operators is another form of coercion, governed by a short list of falsy values: false, 0, '', null, undefined, and NaN — everything else is truthy, including '0' and empty objects/arrays.
+1 + '1' === '11'-*/
3
The practical takeaway most teams land on is to always use === and !== to avoid coercion surprises, and to be explicit about conversions with Number(), String(), or Boolean() when a conversion really is intended. Knowing the coercion rules is still valuable for reading legacy code and for interviews, even if you never rely on them in new code.
===!==Number()String()Boolean()