Sub topic 10
Converting to Numbers
This chapter assumes you can write variables, functions, and operators in JavaScript, and that you can run code in a browser console or Node.js. It also builds on earlier chapters: you should already know the seven primitive types, the difference between null and undefined, and the Number edge cases NaN, -0, and Infinity.
The specification defines an internal rule called ToNumber, an abstract operation that turns any value into a Number. You never call ToNumber directly. The language runs it for you whenever an operation needs a number. Once you know its rules, results like Number("") === 0 and "5" * "2" === 10 stop being surprising.
Where ToNumber Runs
You can trigger numeric conversion explicitly or implicitly.
| Trigger | Example | Kind |
|---|---|---|
| `Number(value)` | `Number("42")` | Explicit |
| Unary plus | `+"42"` | Explicit (but terse) |
| Arithmetic other than `+` | `"6" / "2"` | Implicit |
| Relational comparison with a non-string | `"10" > 9` | Implicit |
| Loose equality with a number | `"1" == 1` | Implicit |
| Global `isNaN`, `Math.*` | `Math.max("3", 1)` | Implicit |
Every row uses the same conversion table, with one exception covered below: Number() accepts BigInt and unary plus does not. Later chapters explain how operators and equality decide when to convert. This chapter covers what the conversion produces.
The Conversion Table for Primitives
console.log(Number(undefined)); // NaN
console.log(Number(null)); // 0
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number(3.5)); // 3.5 (numbers pass through)
console.log(Number("42")); // 42The asymmetry between null and undefined causes real bugs. null means "intentionally empty" and becomes 0. undefined means "no value at all" and becomes NaN. A missing property used in arithmetic therefore poisons the whole calculation with NaN, while a null field quietly counts as zero.
const order = { shipping: null };
console.log(10 + order.shipping * 1); // 10: null became 0
console.log(10 + order.tax * 1); // NaN: undefined became NaNTwo primitive types refuse to convert implicitly:
try {
+Symbol("id");
} catch (e) {
console.log(e.constructor.name); // TypeError
}
try {
+10n;
} catch (e) {
console.log(e.constructor.name); // TypeError
}
console.log(Number(10n)); // 10: Number() handles BigInt explicitlyNumber() is the only conversion that accepts a BigInt. Internally it first runs ToNumeric, which lets a BigInt through, and then converts the BigInt's mathematical value to the nearest Number. Unary plus calls ToNumber directly, and ToNumber throws on BigInt by design, so that precision is never lost silently.
Strings: The Detailed Rules
String conversion causes the most surprises. The engine follows these steps:
- Strip leading and trailing whitespace. This includes spaces, tabs, newlines, and other Unicode whitespace and line terminators.
- If nothing is left, the result is
0. - If the rest is a valid numeric literal, return its value.
- Otherwise, return
NaN. Partial matches are not allowed.
console.log(Number("")); // 0
console.log(Number(" \n\t")); // 0: whitespace only counts as empty
console.log(Number(" 42 ")); // 42
console.log(Number("42px")); // NaN: the whole string must be numeric
console.log(Number("1e3")); // 1000
console.log(Number(".5")); // 0.5
console.log(Number("5.")); // 5
console.log(Number("-12.5")); // -12.5
console.log(Number("Infinity")); // Infinity
console.log(Number("infinity")); // NaN: case-sensitive
console.log(Number("0x1A")); // 26: hex prefix allowed
console.log(Number("0b101")); // 5: binary prefix allowed
console.log(Number("0o17")); // 15: octal prefix allowed
console.log(Number("-0x1A")); // NaN: no sign with a prefix
console.log(Number("1_000")); // NaN: separators work only in source code
console.log(Number("1,000")); // NaN
console.log(Number("-0")); // -0Leading zeros do not switch to octal in string conversion: Number("010") is 10. Only an explicit 0o prefix gives octal.
Objects: Primitive First, Then Number
An object cannot become a number in one step. ToNumber first calls ToPrimitive with the hint "number", then runs the primitive through the table above. The chapter "How Objects Become Primitives" covers ToPrimitive in full. For now, it is enough to know that ordinary objects try valueOf first and fall back to toString. Arrays and plain objects return themselves from valueOf, so their string form decides the result.
console.log(Number([])); // 0: [] -> "" -> 0
console.log(Number([5])); // 5: [5] -> "5" -> 5
console.log(Number([" 7 "])); // 7: whitespace trimmed
console.log(Number([1, 2])); // NaN: "1,2" is not numeric
console.log(Number([null])); // 0: [null] -> "" -> 0
console.log(Number({})); // NaN: "[object Object]"
console.log(Number(new Date(0))); // 0: Date's valueOf returns the timestamp[null] and [undefined] both become "" because Array.prototype.join writes nullish elements as empty strings. That is why Number([undefined]) is 0, while Number(undefined) is NaN.
parseInt and parseFloat Are Different Tools
parseInt and parseFloat do not use ToNumber's string rules. They first convert the argument to a string, then read the longest numeric prefix they can find and ignore the rest.
console.log(parseInt("42px", 10)); // 42
console.log(parseFloat("3.14abc")); // 3.14
console.log(parseInt("", 10)); // NaN: no digits, unlike Number("")
console.log(parseInt(null, 10)); // NaN: parses the string "null"
console.log(parseInt("0x1A")); // 26: hex recognized without a radix
console.log(parseInt("1e3", 10)); // 1: stops at "e"
console.log(parseFloat("1e3")); // 1000: parseFloat understands exponents
console.log(parseInt(0.0000005, 10)); // 5: the number stringifies as "5e-7"
console.log(parseInt("12.9", 10)); // 12: truncates, no rounding
console.log(["1", "2", "3"].map(parseInt)); // [1, NaN, NaN]The last line is a classic trap. map passes (element, index), so the calls become parseInt("2", 1) and parseInt("3", 2). Radix 1 is invalid, and "3" is not a binary digit. Write .map((s) => parseInt(s, 10)) or .map(Number) instead.
| Input | `Number(x)` | `parseInt(x, 10)` | `parseFloat(x)` |
|---|---|---|---|
| `""` | 0 | NaN | NaN |
| `"42px"` | NaN | 42 | 42 |
| `"1e3"` | 1000 | 1 | 1000 |
| `null` | 0 | NaN | NaN |
| `true` | 1 | NaN | NaN |
| `"0x1A"` | 26 | 0 | 0 |
Common Errors and How to Avoid Them
- Treating blank input as zero. Check
str.trim() === ""before you callNumber. - Using global
isNaNfor validation.isNaNruns ToNumber first, soisNaN("")isfalse. Convert first, then test withNumber.isNaN. - Calling
parseIntwithout a radix. Always pass10unless you really want hex prefixes to be detected. - Using unary plus on values that might be BigInt.
+valuethrows. UseNumber(value)if you need to accept both. - Expecting
Numberto accept formatted numbers."1,000"and"$5"giveNaN. Strip formatting yourself, or useparseFloatwhen a trailing unit is acceptable.
A strict parser combines these rules:
function toStrictNumber(input) {
if (typeof input !== "string" || input.trim() === "") return null;
const n = Number(input);
return Number.isFinite(n) ? n : null;
}
console.log(toStrictNumber(" 12.5 ")); // 12.5
console.log(toStrictNumber("")); // null
console.log(toStrictNumber("12px")); // null
console.log(toStrictNumber("Infinity")); // nullExercise
Predict each result without running it: Number(" "), Number([undefined]), Number(["1", "2"]), +false, Number("0b11"), parseInt("0b11", 10).
Show answer
0 (whitespace only counts as empty), 0 ([undefined] joins to ""), NaN ("1,2" is not numeric), 0, 3 (binary literal), 0 (parseInt reads the digit "0" and stops at "b").
Exercise
Why does Number(null) + Number(undefined) produce NaN, and which single change makes the sum 0?
Show answer
Number(null) is 0, but Number(undefined) is NaN, and any arithmetic with NaN gives NaN. Replace undefined with null, or default it first with value ?? 0, so both operands become 0.
Exercise
A teammate writes if (!isNaN(field)) save(Number(field)) to validate a text input. Name two inputs that pass this check but should probably be rejected.
Show answer
"" and " " both pass, because ToNumber turns them into 0 and isNaN(0) is false. They are saved as 0. "Infinity" also passes and is saved as Infinity.