Sub topic 5
NaN, Infinity, and -0
This chapter assumes you can run JavaScript in Node.js or a browser console, and that you know === and typeof. It also builds on the earlier chapters about the IEEE 754 double format and the arithmetic operators. IEEE 754 sets aside some bit patterns for results that are not ordinary numbers. JavaScript exposes three of them: NaN, Infinity (with -Infinity), and negative zero. All three have typeof equal to "number". All three pass silently through arithmetic, which is why they cause bugs far from where they first appear.
Where these values come from
JavaScript arithmetic never throws for bad math. When an operation has no meaningful numeric result, the result is NaN ("Not a Number"). When a result is too large to represent, or a nonzero number is divided by zero, the result is Infinity or -Infinity. When a result is zero but arrived from the negative side, the result is -0.
// NaN: an undefined or unrepresentable result
console.log(0 / 0); // NaN
console.log(Infinity - Infinity); // NaN
console.log(Infinity * 0); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(Number("abc")); // NaN
console.log(typeof NaN); // "number"
// Infinity: overflow or division of a nonzero value by zero
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Number.MAX_VALUE * 2); // Infinity
console.log(Number.MAX_VALUE + 1); // 1.7976931348623157e+308 (rounded away, no overflow)
// -0: a zero that remembers its sign
console.log(0 * -1); // -0
console.log(Math.round(-0.4)); // -0
console.log(-1e-400); // -0 (underflow)Number.MAX_VALUE + 1 does not overflow. Adding 1 is far smaller than the gap between neighboring doubles at that size, so the sum rounds back to MAX_VALUE. Overflow to Infinity only happens when the true result is past the largest double after rounding.
NaN
Propagation
Almost every operation with a NaN operand returns NaN. One bad input early in a calculation spreads to the final total, and nothing throws an error along the way.
const prices = [10, 20, Number("n/a"), 5];
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total); // NaN, and the bad entry is not named anywhereA few operations do not propagate it. NaN ** 0 is 1, and Math.min() and Math.max() ignore nothing (any NaN argument gives NaN), but string concatenation turns it into the text "NaN", so the failure shows up in the UI as a label instead of an error.
NaN is not equal to anything, including itself
IEEE 754 defines every comparison involving NaN as false, except !==, which is true.
const x = NaN;
console.log(x === NaN); // false
console.log(x == NaN); // false
console.log(x !== x); // true: the only value with this property
console.log(x < 1, x > 1, x >= 1); // false false false
console.log(Number.isNaN(x)); // true
console.log(Object.is(x, NaN)); // trueBecause x === NaN is always false, a check like if (value === NaN) never runs its branch. Use Number.isNaN(value). The older global isNaN converts its argument to a number first, so isNaN("abc") is true even though "abc" is a string. The validation chapter compares these functions in detail.
Gotcha: NaN in arrays and sorting
Array methods do not agree on how to find NaN. indexOf uses ===. includes uses an algorithm called SameValueZero, which treats NaN as equal to NaN.
const values = [1, NaN, 3];
console.log(values.indexOf(NaN)); // -1
console.log(values.includes(NaN)); // true
console.log(values.findIndex(Number.isNaN)); // 1
const set = new Set([NaN, NaN]);
console.log(set.size); // 1Sorting is a quieter problem. A comparator such as (a, b) => a - b returns NaN whenever NaN is involved. The sort treats that as "equal", which breaks the ordering the algorithm depends on. The final order then depends on the engine and on where the NaN started. Filter out or explicitly place NaN values before sorting.
Infinity
Infinity behaves like the mathematical limit in most operations. It is larger than every finite number, and -Infinity is smaller than every finite number.
console.log(Infinity > Number.MAX_VALUE); // true
console.log(Infinity + 1 === Infinity); // true
console.log(Infinity === Infinity); // true (unlike NaN)
console.log(1 / Infinity); // 0
console.log(-1 / Infinity); // -0
console.log(Number.POSITIVE_INFINITY === Infinity); // trueInfinity is useful as a starting value. A running minimum can start at Infinity, because any real value will be smaller. This is also why Math.max() with no arguments returns -Infinity.
function smallest(list) {
let min = Infinity;
for (const n of list) if (n < min) min = n;
return min; // Infinity for an empty list
}
console.log(smallest([4, 2, 9])); // 2
console.log(smallest([])); // InfinityThe test Number.isFinite(value) is false for NaN, Infinity, and -Infinity. It is usually the right guard for "this is a usable number".
Negative zero
IEEE 754 stores a sign bit separately from the magnitude, so zero exists as both +0 and -0. Most of the language hides the difference.
const negZero = -0;
console.log(negZero === 0); // true
console.log(negZero < 0); // false
console.log(String(negZero)); // "0"
console.log(`${negZero}`); // "0"
console.log(JSON.stringify(negZero)); // "0"
console.log(negZero.toFixed(2)); // "0.00" in current engines
console.log(Object.is(negZero, 0)); // false
console.log(Object.is(negZero, -0)); // true
console.log(1 / negZero); // -Infinity
console.log(Math.sign(negZero)); // -0The sign is visible in three places: division (1 / -0 is -Infinity), Object.is, and functions that preserve the sign such as Math.sign, Math.round, and Math.atan2. Math.atan2(0, -1) is π, but Math.atan2(-0, -1) is -π, so an angle can flip sides. A temperature readout may show "-0°" because Math.round(-0.3) returns -0 and some formatters print the sign. Intl.NumberFormat does print it: new Intl.NumberFormat("en-US").format(-0) gives "-0".
To remove the sign, add zero (-0 + 0 is +0), or use value || 0, which also maps NaN to 0. That may or may not be what you want.
function normalizeZero(n) {
return n === 0 ? 0 : n; // turns -0 into +0, leaves everything else alone
}
console.log(Object.is(normalizeZero(-0), 0)); // trueTo detect -0 without Object.is, use n === 0 && 1 / n === -Infinity.
Choosing an equality check
JavaScript has three equality algorithms. They differ only on NaN and on the two zeros.
| Algorithm | Used by | `NaN` vs `NaN` | `0` vs `-0` |
|---|---|---|---|
| Strict equality | `===`, `indexOf`, `switch` | not equal | equal |
| SameValueZero | `includes`, `Map`, `Set` | equal | equal |
| SameValue | `Object.is` | equal | not equal |
Use === for ordinary values, Number.isNaN when testing for NaN, and Object.is only when the sign of zero matters to your logic.
Exercise
A function computes an average as sum / items.length. What does it return for an empty array, and what does it return if one item is the string "x" converted with Number()? Write a guard that returns null in both cases.
Show answer
For an empty array the sum is 0 and the length is 0, so 0 / 0 gives NaN. A Number("x") item makes the sum NaN, so the average is NaN as well. A guard: const avg = sum / items.length; return Number.isFinite(avg) ? avg : null;. Number.isFinite rejects NaN as well as ±Infinity.
Exercise
Predict the output of each line: [NaN].indexOf(NaN), [NaN].includes(NaN), [-0].includes(0), Object.is(Math.round(-0.2), 0), new Map([[-0, "a"]]).get(0).
Show answer
-1, true, true, false (Math.round(-0.2) is -0), and "a" (Map uses SameValueZero, so -0 and 0 are the same key).
Exercise
Why does Number.MAX_VALUE + 1 === Number.MAX_VALUE print true, while Number.MAX_VALUE * 2 is Infinity?
Show answer
Near MAXVALUE the gap between neighboring doubles is about 2e292, so adding 1 rounds back to MAXVALUE. Doubling it gives a true result beyond the largest finite double. That result rounds to Infinity, which is overflow.