Glossary / Type coercion
Type coercion
Type coercion converts a value from one type to another. JavaScript performs some conversions explicitly (Number(value)) and others implicitly as part of operators, comparisons, property-key conversion, and built-in APIs. Coercion is a core language feature, but implicit conversions can obscure intent and are not a substitute for validating external data.
Primitive conversion and operators
When an operation needs a primitive from an object, JavaScript can consult Symbol.toPrimitive, valueOf, and toString according to the conversion hint. Objects can therefore customize how they participate in arithmetic or string construction. For built-in objects these hooks may be meaningful; for arbitrary objects, conversion often yields a generic string such as "[object Object]".
The + operator first performs primitive conversion and concatenates if either resulting primitive is a string; otherwise it performs numeric addition. Most other arithmetic operators convert operands to numbers. Relational comparisons have their own conversion rules, and == uses abstract equality rather than a single universal conversion.
"5" + 1; // "51"
"5" - 1; // 4
Number(""); // 0, which may not be intended input handling
Explicit conversion is more readable but still may accept surprising input. Number(null) is zero; Number(undefined) is NaN; Boolean("false") is true. Parse and validate according to the expected grammar, range, and domain—not merely by converting.
Security and reliability
Never build HTML, SQL, shell commands, or URLs by interpolating values and assuming type conversion provides escaping. Use context-specific safe APIs and parameterized interfaces. Objects with custom conversion hooks can run code during coercion, so avoid coercing untrusted arbitrary objects in sensitive paths.
For domain boundaries, define normalization once: accepted input types, whitespace policy, locale, range, and error behavior. Reject ambiguous values rather than relying on implicit conversion.
Interview questions
- Why does
"5" + 1concatenate but"5" - 1subtract? Plus supports string concatenation after primitive conversion; subtraction requires numeric conversion. - Is
Number(value)validation? No; it performs conversion, and values such as empty string and null become zero. - Can an object control its primitive conversion? Yes, using
Symbol.toPrimitive,valueOf, andtoStringbehavior. - Does coercion sanitize HTML or SQL? No. Use safe output encoding or parameterized APIs.