Sub topic 9
Converting to Numbers
This chapter assumes you know the eight JavaScript types and the Number edge cases covered earlier, mainly NaN and Infinity. It explains the rules behind ToNumber, the internal operation JavaScript uses whenever it needs a number from some other value.
Where ToNumber runs
ToNumber runs when you call Number(value) or apply unary plus (+value). It also runs implicitly inside -, *, /, %, and **, and inside relational comparisons. The rules are the same in each case, so if you learn them once you can predict all of these operators.
The rules by input type
| Input | Result |
|---|---|
| `undefined` | `NaN` |
| `null` | `0` |
| `true` / `false` | `1` / `0` |
| number | unchanged |
| string | parsed as a numeric literal (see below) |
| symbol | throws `TypeError` |
| bigint | throws `TypeError` (though `Number()` converts it) |
| object | ToPrimitive with the "number" hint, then ToNumber on the result |
null and undefined give different results: null becomes 0, while undefined becomes NaN. This is why 1 + null is 1 and 1 + undefined is NaN.
String parsing
JavaScript first trims leading and trailing whitespace from the string, including line breaks. Then the whole remaining string must be a valid numeric literal, or the result is NaN. An empty or whitespace-only string becomes 0, which causes a lot of form-validation bugs.
console.log(Number("")); // 0
console.log(Number(" \n ")); // 0
console.log(Number(" 42 ")); // 42
console.log(Number("1e3")); // 1000
console.log(Number("0x1F")); // 31
console.log(Number("0b101")); // 5
console.log(Number("-Infinity"));// -Infinity
console.log(Number("42px")); // NaN
console.log(Number("1_000")); // NaN: separators work only in source code
console.log(Number("1,5")); // NaNObjects
ToNumber turns an object into a primitive first (the next chapter covers how), then converts that primitive. For arrays, the primitive is usually the joined string:
console.log(Number([])); // 0: [] becomes "", then 0
console.log(Number([5])); // 5: [5] becomes "5"
console.log(Number([1, 2])); // NaN: "1,2"
console.log(Number({})); // NaN: "[object Object]"
console.log(Number(new Date(0))); // 0: Date gives its timestampNumber() versus parseInt and parseFloat
parseInt and parseFloat use different rules from ToNumber. They read a leading numeric prefix and ignore whatever comes after it.
console.log(parseInt("42px", 10)); // 42
console.log(parseFloat("3.14abc")); // 3.14
console.log(parseInt("", 10)); // NaN, where Number("") is 0
console.log(parseInt("0x1F", 16)); // 31
console.log(Number(10n), +"7"); // 10 7
// console.log(+10n); // TypeError: Cannot convert a BigInt value to a numberCommon errors
- Treating
Number("")as invalid input. It returns0and passesNumber.isNaNchecks. - Calling
+on a BigInt. UseNumber(big)instead, and accept that values aboveNumber.MAX_SAFE_INTEGERlose precision. - Passing
parseIntas a callback:["1", "2", "3"].map(parseInt)gives[1, NaN, NaN]becausemappasses the index as the radix.
Exercise
Predict the results of Number(null), Number(undefined), Number(" 0x10 "), Number([" 7 "]), and parseInt("12.9em", 10).
Show answer
0, NaN, 16, 7, and 12. null becomes 0 and undefined becomes NaN. The string " 0x10 " is trimmed and parsed as hex. [" 7 "] becomes the string " 7 ", which trims to 7. parseInt reads the leading digits "12" and stops at the dot.
Exercise
A form field returns "" when it is left blank. Why does if (!Number.isNaN(Number(input))) accept the blank field, and how would you fix it?
Show answer
Number("") is 0, which is not NaN, so the check passes. Reject the blank field first, for example with input.trim() !== "" && !Number.isNaN(Number(input)).