Normalize numeric input
Parsing user input or form values before arithmetic.
JS Puzzles · Const
JavaScript automatically converts values when an operation expects another type. The conversion path depends on the context and can involve primitive, numeric, BigInt, string, or object-to-primitive rules.
JavaScript may implicitly convert a value when an operation expects another type. The conversion rules depend on the target context: primitive, numeric, BigInt, or string conversion; objects first try Symbol.toPrimitive and then valueOf() or toString().
const values = ["5", 9, null, undefined, true];
for (const value of values) {
console.log(String(value), Number(value));
}
console.log("5" + 9); // "59"
console.log(Number("5") + 9); // 14The first loop shows explicit string and number conversion. The final lines contrast string concatenation caused by + with explicit numeric conversion.
Parsing user input or form values before arithmetic.
Building APIs that accept values from multiple primitive types.
Defining custom object behavior for arithmetic or interpolation.
Type coercion is the automatic conversion of a value from one type to another. JavaScript permits this because it is weakly typed, so operations can convert mismatched operands instead of immediately throwing a type error.
Follow-up: How does object conversion begin? JavaScript first checks Symbol.toPrimitive, then falls back to valueOf() and toString() according to the conversion hint.
The + operator can concatenate when string conversion is selected, so a numeric operand may become text. Explicit Number(value) conversion makes numeric addition intentional and avoids relying on that choice.
Follow-up: What happens with Number(null), Number(undefined), and Number(true)? They become 0, NaN, and 1 respectively.
Object-to-primitive conversion uses Symbol.toPrimitive first. If it is absent, JavaScript tries valueOf() and toString() in the order determined by the hint.
Follow-up: For a string hint, the order is toString() followed by valueOf(); for numeric conversion, the preferred order is Symbol.toPrimitive("number"), valueOf(), then toString().
Primitive coercionNumeric coercionString coercionSymbol.toPrimitivevalueOf()toString()