Why Math.max() returns -Infinity in JavaScript
Beginner · 3 min read
Finding the biggest or smallest number in a list is one of the first things real programs do: the highest score, the coldest day, the cheapest flight. Close behind is clamping, which means keeping a value inside a range, like a volume slider that can't go below 0 or above 100.
In this tutorial you will use Math.min and Math.max on a list of readings, write a clamp function, and find out why Math.max() with nothing inside the brackets gives -Infinity. You need to know what an array is and how to write a small arrow function.
Math.min and Math.max
Both take any number of arguments, separated by commas, and return the smallest or largest:
console.log(Math.min(23, 41, 12)); // 12
console.log(Math.max(23, 41, 12)); // 41
Spreading an array
Your numbers usually live in an array, not in a list of arguments. The spread syntax, three dots before the array, unpacks it into separate arguments:
const xs = [23, 41, 12];
console.log(Math.max(...xs)); // 41, the same as Math.max(23, 41, 12)
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
4 Smallest, largest, and clamping to a range
easyFind the smallest and largest of a list, then write clamp(n, low, high). Then explain why Math.max() with no arguments is -Infinity.
Stuck? Three hints, smallest first
- 1. Both take any number of arguments, so an array needs spreading:
Math.max(...xs). - 2. They start from the identity for their comparison, which is why the empty call returns an infinity.
- 3.
clampisMath.minofMath.max, in that nesting.
Step 1: smallest and largest of a list
const readings = [23, 41, 12, 38];
console.log(Math.max(readings)); // NaN
console.log(Math.min(...readings)); // 12
console.log(Math.max(...readings)); // 41
The first line is the wrong turn everyone takes once. Passed an array without the dots, Math.max gets a single argument, tries to turn the whole array into one number, and fails with NaN ("Not a Number"). With the dots, it sees four separate numbers.
Step 2: call them with nothing
console.log(Math.max()); // -Infinity
console.log(Math.min()); // Infinity
This looks like a bug, but it has a reason. Picture how Math.max works inside: it keeps a "best so far" and compares each argument against it. The starting value has to lose to any real number, so it starts at -Infinity, the lowest value there is. With no arguments, nothing ever beats it, so that starting value is what comes back. Math.min starts at Infinity for the same reason.
This matters because an empty array gives the same result:
console.log(Math.max(...[])); // -Infinity
If that value flows into a chart or a total, you get nonsense with no error. Check xs.length first when the list might be empty.
Step 3: one NaN spoils everything
console.log(Math.max(1, NaN, 3)); // NaN
Any comparison with NaN is false, so once a NaN gets in, the answer is NaN. If your data might contain bad values, filter them out before you look for the maximum.
Step 4: write clamp
To keep n between low and high, do it in two moves:
Math.max(n, low)lifts anything belowlowup tolow.Math.min(..., high)pulls anything abovehighdown tohigh.
const clamp = (n, low, high) => Math.min(Math.max(n, low), high);
console.log(clamp(5, 1, 10)); // 5
console.log(clamp(-2, 1, 10)); // 1
console.log(clamp(99, 1, 10)); // 10
A value already in range passes through both untouched. It feels backwards at first that the lower limit uses max, but read it as "at least low" and it makes sense.
Step 5: very long arrays
Spreading turns every item into a separate argument, and engines have a limit on how many arguments one call can take. A big enough array throws a RangeError. The exact limit depends on the engine. reduce walks the array one item at a time instead, so it has no such limit:
const maxByReduce = (xs) => xs.reduce((m, n) => Math.max(m, n), -Infinity);
console.log(maxByReduce([23, 41, 12, 38])); // 41
console.log(maxByReduce([])); // -Infinity
It starts from -Infinity, the same starting point Math.max uses, so an empty array gives the same answer both ways.
The full solution
The answer panel finds the smallest and largest reading, shows the empty calls, the NaN case, clamp, and the reduce version. The checks underneath confirm each result. Press Run to see the output.
const readings = [23, 41, 12, 38];
const clamp = (n, low, high) => Math.min(Math.max(n, low), high);
// Spread has an argument limit, so a very long array wants reduce instead.
const maxByReduce = (xs) => xs.reduce((m, n) => Math.max(m, n), -Infinity);
console.log('min :', Math.min(...readings));
console.log('max :', Math.max(...readings));
console.log('no args :', Math.max(), 'and', Math.min(), '<- the identities');
console.log('with NaN :', Math.max(1, NaN, 3));
console.log('clamped :', [clamp(5, 1, 10), clamp(-2, 1, 10), clamp(99, 1, 10)]);
console.log('by reduce:', maxByReduce(readings));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the smallest of the list', Math.min(...readings), 12);
test('the largest of the list', Math.max(...readings), 41);
test('Math.max with no arguments is -Infinity', Math.max() === -Infinity, true);
test('and Math.min with none is +Infinity', Math.min() === Infinity, true);
test('so the max of an empty array is -Infinity, not 0', Math.max(...[]) === -Infinity, true);
test('one NaN poisons the whole comparison', Number.isNaN(Math.max(1, NaN, 3)), true);
test('clamp leaves an in-range value alone and pulls the rest in', [clamp(5, 1, 10), clamp(-2, 1, 10), clamp(99, 1, 10)], [5, 1, 10]);
test('reduce gives the same answer without spreading', maxByReduce(readings), 41);
test('and it handles the empty case the same way', maxByReduce([]) === -Infinity, true);
The empty-call results are not a quirk, they are the identity elements: starting from -Infinity means the first real argument always wins, which is exactly how reduce has to be seeded too. It does mean Math.max(...xs) on an empty array gives -Infinity rather than throwing, and that value then flows into your chart axis or your total. Check the length first.
Two limits on the spread form. A very large array can exceed the engine's argument count and throw a RangeError — around 100k elements, engine-dependent — and one NaN anywhere makes the answer NaN, since every comparison with NaN is false. The reduce version fixes the first and inherits the second.
Common mistakes
- Forgetting the spread.
Math.max(readings)isNaN. WriteMath.max(...readings). - Assuming an empty list gives 0.
Math.max(...[])is-Infinity. Check the length first. - Nesting clamp the wrong way round.
Math.max(Math.min(n, low), high)always returnshigh. The inner call useslowwithmax.
Try it yourself
- Write
range(xs)that returns the largest value minus the smallest. - Use
clampto keep a percentage between 0 and 100, and test it with -5, 50 and 120. - Change
maxByReduceintominByReduce. What should its starting value be?