Convert numeric strings
Normalize form, query, or configuration text before arithmetic.
JS Puzzles · Const
Number coercion converts JavaScript values to numbers using type-specific rules. Numbers pass through, primitive values map predictably, strings are parsed, and some values produce NaN or throw.
JavaScript’s number coercion converts values according to their type: numbers stay unchanged, null and booleans map to numeric values, strings are parsed, and unsupported values can produce NaN or throw. Objects are first reduced to a primitive using their numeric conversion hooks.
Number(value)| Name | Type | Description |
|---|---|---|
value | any | The value to convert to a number. |
A number primitive; conversion can produce NaN or throw TypeError for unsupported inputs.
const values = [undefined, null, true, false, "", " ", "42", 3.14];
console.log(values.map(value => [String(value), Number(value)]));Run this to inspect how representative JavaScript values become numbers.
Normalize form, query, or configuration text before arithmetic.
Detect invalid numeric input after conversion.
Understand implicit conversions in arithmetic and built-in APIs.
Number coercion leaves numbers unchanged, maps undefined to NaN, null to 0, true to 1, and false to 0. Empty or whitespace-only strings also become 0, while numeric strings are parsed.
Follow-up: What happens to a BigInt? Number coercion throws TypeError, whereas Number(bigInt) converts it and may lose precision.
Unary plus performs the same number-coercion steps as most built-ins that expect numbers. Number(value) follows the same process, except it converts BigInt rather than throwing.
Follow-up: Why can Number(bigInt) be dangerous? A Number may not preserve the BigInt’s exact value when it exceeds the safe integer range.
For objects, JavaScript first obtains a primitive by trying Symbol.toPrimitive with the number hint, then valueOf(), then toString(). It converts the resulting primitive to a number.
Follow-up: What if all conversion methods fail to provide a usable primitive? The object-to-primitive operation throws rather than completing numeric conversion.
Number()unary plus (+)Symbol.toPrimitivevalueOf()toString()BigInt