Type Coercion
Type coercion is the engine converting a value from one type to another because an operator or built-in asked for it. Some conversions are explicit (Number(x)); most of the surprising ones are implicit.
Detailed Explanation
JavaScript is dynamically typed and its operators are overloaded. + adds numbers or concatenates strings. < compares numbers or strings. if wants a boolean. When the types you wrote do not match what the operator needs, the spec runs a conversion. That conversion is coercion.
The important abstract operations have names you will see in explanations:
- ToPrimitive turns an object into a primitive, trying
Symbol.toPrimitive, thenvalueOf, thentoString(or the other way around if the hint is"string"). - ToString turns a value into a string.
nullbecomes"null". Arrays join their elements with commas. Objects become"[object Object]"unless they overridetoString. - ToNumber turns a value into a number.
""andnullbecome0." 8 "becomes8.undefinedand"oops"becomeNaN.truebecomes1. - ToBoolean produces the familiar truthy/falsy split.
- ToBigInt is stricter and throws on most leftovers.
Explicit conversions are the ones you can see: Number(x), String(x), Boolean(x), parseInt(x, 10), parseFloat(x), x.toString(), +x, !!x. Use these at system boundaries: query strings, form fields, JSON that arrived as text, environment variables.
Implicit conversions are the ones you cannot see. 1 + "2" is "12". 1 - "2" is -1, because - is only numeric. [] + {} is "[object Object]". {} + [] at the start of a statement is treated as a block plus +[], which is 0. == is a coercion engine of its own.
parseInt and Number disagree. Number("8px") is NaN. parseInt("8px", 10) is 8. parseInt("08", 10) is 8; always pass the radix. Number("") is 0; parseInt("") is NaN.
What it costs you: values that look right in a log and compute wrong. "10" + 1 is "101" in a template you did not mean to write. A comparison userId == 0 after an API change to string ids. The fix is to convert once, on purpose, and then use ===.
Reach for explicit conversion at the edge. Keep the core of a function on values that already have the right type. Prefer Number.isFinite over typeof x === "number" when you need a usable number, because typeof NaN is "number".
Code Examples
console.log(1 + "2"); // => 12
console.log(1 - "2"); // => -1
console.log(+" 8 "); // => 8
console.log(Number("")); // => 0
console.log(Number("8px")); // => NaN
console.log(parseInt("8px", 10)); // => 8
console.log(Boolean([])); // => true
console.log(Boolean("")); // => falseconsole.log([1, 2].toString()); // => 1,2
console.log(String({ a: 1 })); // => [object Object]
console.log(Number(null)); // => 0
console.log(Number(undefined)); // => NaN
console.log(Number(true)); // => 1function asCount(raw) {
const n = Number(raw);
if (!Number.isFinite(n) || n < 0) {
throw new TypeError(`not a count: ${raw}`);
}
return n;
}
console.log(asCount("3")); // => 3
try {
asCount("3px");
} catch (err) {
console.log(err.message); // => not a count: 3px
}Common Gotchas
`+` prefers strings once either side is a string
`1 + 2 + "3"` is `"33"`. Convert before you add if you meant arithmetic.
`Number("")` is `0` and `Number(null)` is `0`
empty input is not a number you intended. Reject it with `Number.isFinite` plus a source check.
`==` hides coercion
`[] == 0` is `true`. Use `===` after an explicit convert.
Objects convert through `ToPrimitive`
a class can define `Symbol.toPrimitive` or `valueOf` to control `+` and `==`. Dates convert to strings under `+`.