Type Coercion Theory
Type coercion is JavaScript's implicit or explicit conversion process between primitives, which affects equality, arithmetic, boolean checks, and many edge-case behaviors.
What it is
JavaScript operations often require operands of certain types. When values differ from expected types, JavaScript converts them according to specification rules.
Coercion can be explicit, such as Number(value), String(value), or Boolean(value), or implicit, such as string concatenation and loose equality.
Understanding coercion prevents bugs around null, undefined, empty strings, NaN, and comparison operators.
Interview framing: define Type Coercion in one sentence, then explain one concrete runtime behavior and one common pitfall with a short code example.
How it works
- Step 1: an operator or language construct evaluates operand types.
- Step 2: if required, JavaScript applies conversion algorithms to one or both operands.
- Step 3: operation proceeds using converted values and returns a result.
- Step 4: further expressions may trigger additional coercions, especially in chained comparisons or mixed-type arithmetic.
Common mistakes
Using loose equality without understanding rules
== applies multi-step coercion that can produce surprising results across strings, numbers, booleans, null, and undefined.
Fix: Default to === and use == only in deliberate, well-understood cases.
Treating all non-number strings as NaN conversions
Some strings convert unexpectedly, such as Number('') and Number(' ') returning 0.
Fix: Validate and normalize input before numeric conversion.
Relying on truthy and falsy checks for business rules
Values like 0, '', and NaN are falsy but may represent valid user input.
Fix: Use explicit checks for nullish values or domain-specific conditions.
Interview questions
Common interview prompts with concise model answers.
Is NaN equal to itself?
No. NaN is the only JavaScript value that is not equal to itself. Use Number.isNaN to test it reliably.
console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // true
console.log([] == false); // true (coercion)Why is [] == false true in JavaScript?
Loose equality triggers coercion steps that convert values before comparison, leading to unintuitive but spec-defined results.
Should I ever use == ?
It can be acceptable for specific patterns like value == null to match null or undefined, but use it intentionally and sparingly.
Does Boolean('false') return false?
No. Non-empty strings are truthy, so Boolean('false') returns true.
Related concepts
Continue with these concepts to strengthen your mental model.