Find the max value with Math.max and reduce in JavaScript
Intermediate · 4 min read
Finding the biggest or smallest value in a list comes up everywhere: the highest score, the cheapest fare, the latest date, the hottest day of the month. JavaScript gives you two ways to do it, and most of the time they agree. This lesson is about the times they don't.
In this tutorial you will find the largest and smallest value with reduce, then with Math.max and spread. Then you will find two inputs where the two answers differ: a list containing NaN, and a list too long to spread. You should know arrays, arrow functions and the basics of reduce.
Math.max and spread
Math.max takes any number of separate arguments and returns the largest. It doesn't take an array. Spread, written ..., unpacks an array into separate arguments.
console.log(Math.max(3, 9, 4)); // 9
console.log(Math.max(...[3, 9, 4])); // 9: the same call
console.log(Math.max([3, 9, 4])); // NaN: one argument, an array
The last line passes the whole array as one argument. Math.max can't turn an array into a number, so it gives NaN.
The starting value for a maximum
What is the largest of no numbers at all? Math.max() answers -Infinity, a value smaller than every number. That is a good starting point: whatever you compare it with is bigger, so the first real number always replaces it.
console.log(Math.max()); // -Infinity
console.log(Math.min()); // Infinity
console.log(5 > -Infinity); // true
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
31 Largest and smallest
fairFind the largest and smallest value two ways: with reduce, and with Math.max and spread. Then find a case where the two disagree.
Stuck? Three hints, smallest first
- 1.
Math.max()with no arguments returns-Infinity, which is the correct identity for a maximum. - 2. Spread turns every element into an argument, and there is a limit on how many arguments a call can take.
- 3.
Math.maxpropagatesNaN. A comparison liken > bestis always false againstNaN, so it skips it.
Step 1: largest and smallest with reduce
Carry the best value so far. At each number, keep whichever is bigger.
const largest = (xs) => xs.reduce((best, n) => (n > best ? n : best), -Infinity);
const smallest = (xs) => xs.reduce((best, n) => (n < best ? n : best), Infinity);
console.log(largest([3, 9, 4])); // 9
console.log(smallest([3, 9, 4])); // 3
console.log(largest([])); // -Infinity
best starts at -Infinity for the largest and Infinity for the smallest. An empty list gives back the starting value instead of crashing. Whether -Infinity is a sensible answer for your page is up to you, but at least it is a clear one.
Step 2: the short version
console.log(Math.max(...[3, 9, 4])); // 9
console.log(Math.min(...[3, 9, 4])); // 3
Same answers, less code. For short, clean lists this is the version most people write.
Step 3: one bad value
Real data is not always clean. Say one reading failed and came through as NaN.
const largest = (xs) => xs.reduce((best, n) => (n > best ? n : best), -Infinity);
console.log(Math.max(1, NaN, 3)); // NaN
console.log(largest([1, NaN, 3])); // 3
console.log(NaN > 1, NaN < 1); // false false
Here they disagree. Math.max returns NaN if any argument is NaN: one bad value spoils the whole answer. The reduce version uses n > best, and every comparison with NaN is false, as the last line shows. So NaN never wins, and it is simply skipped.
Which one is right? It depends. Skipping bad data quietly is not always what you want, since it can hide a real problem. But you should know which behavior you are getting.
Step 4: a very long list
Spread turns every item into a separate argument, and an engine can only accept so many arguments in one call. Try 200,000:
const largest = (xs) => xs.reduce((best, n) => (n > best ? n : best), -Infinity);
const big = Array.from({ length: 200000 }, (_, i) => i);
try {
console.log(Math.max(...big));
} catch (e) {
console.log(e.constructor.name);
}
console.log(largest(big)); // 199999
In node 26 the spread line throws a RangeError ("Maximum call stack size exceeded"). The exact limit differs between engines, which is why the panel prints what yours does. The reduce version looks at one number at a time, so the length of the list doesn't matter.
Step 5: return the whole record
Often you don't want the lowest price, you want the fare that has it. With reduce you can carry the whole object.
const fares = [
{ route: 'Yaba', price: 450 },
{ route: 'Ikeja', price: 900 },
{ route: 'Ojota', price: 300 },
];
const cheapest = (rows) => rows.reduce((best, r) => (r.price < best.price ? r : best));
console.log(cheapest(fares).route); // Ojota
There is no starting value here, so the first fare starts as best. That is fine for a list you know is not empty. On an empty list this would throw, so add a check if the list might be empty.
Math.min(...fares.map((f) => f.price)) would give you 300, and then you would have to search the list again to find which fare it was.
The full solution
The panel defines largest, smallest and cheapest, compares them with Math.max and Math.min, and then tries both on a NaN and on 200,000 values. Press Run and see what your browser prints for the long list.
const largest = (xs) => xs.reduce((best, n) => (n > best ? n : best), -Infinity);
const smallest = (xs) => xs.reduce((best, n) => (n < best ? n : best), Infinity);
// Pick the record with the smallest price, not just the price itself.
const cheapest = (rows) => rows.reduce((best, r) => (r.price < best.price ? r : best));
const fares = [
{ route: 'Yaba', price: 450 },
{ route: 'Ikeja', price: 900 },
{ route: 'Ojota', price: 300 },
];
const big = Array.from({ length: 200000 }, (_, i) => i);
const spreadBig = (() => {
try { return String(Math.max(...big)); } catch (e) { return e.constructor.name; }
})();
console.log('reduce :', largest([3, 9, 4]), smallest([3, 9, 4]));
console.log('Math.max:', Math.max(...[3, 9, 4]), Math.min(...[3, 9, 4]));
console.log('Math.max() with no arguments:', Math.max(), '<- the identity for a maximum');
console.log('--- where they differ ---');
console.log('Math.max(1, NaN, 3) :', Math.max(1, NaN, 3), '<- one bad value poisons it');
console.log('largest([1, NaN, 3]):', largest([1, NaN, 3]), '<- the comparison skips it');
console.log('cheapest record :', cheapest(fares).route);
console.log('200,000 values through spread:', spreadBig);
console.log('the same through reduce :', largest(big));
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('reduce finds the largest', largest([3, 9, 4]), 9);
test('and the smallest', smallest([3, 9, 4]), 3);
test('Math.max with spread agrees', Math.max(...[3, 9, 4]), 9);
test('Math.max of nothing is -Infinity', Math.max() === -Infinity, true);
test('so an empty array reduces to the identity, not an error', largest([]) === -Infinity, true);
test('Math.max is poisoned by a single NaN', Number.isNaN(Math.max(1, NaN, 3)), true);
test('while the comparison-based reduce steps over it', largest([1, NaN, 3]), 3);
test('reduce handles an array too long to spread', largest(big), 199999);
test('and reduce can return the whole record, not just the number', cheapest(fares).route, 'Ojota');
Math.max(...xs) is the short form and it has two real limits. Spread becomes one argument per element, and an engine will throw RangeError somewhere over a hundred thousand of them — the log above shows what your engine does with 200,000. And a single NaN anywhere makes the answer NaN.
The reduce version is longer and neither problem applies: it looks at one value at a time, and n > best is false for NaN so the bad value is simply passed over. Which behaviour you want is a decision — silently ignoring corrupt data is not always right — but you should know which one you are getting.
cheapest is the pattern to take away: reduce over the records rather than over the prices, and you keep the whole object instead of having to search for it again.
Common mistakes
- Passing the array straight to
Math.max.Math.max([3, 9])isNaN. Spread it:Math.max(...xs). - Starting the maximum at
0. For a list of negative numbers,0wins and is wrong. Start at-Infinity. - Spreading a huge list. Past some engine limit, spread throws a
RangeError. Usereducefor long or unknown-length lists.
Try it yourself
- Find the highest and lowest temperature in
[21, 23, 19, 25, 22]in onereducethat returns{ min, max }. - Find the longest word in
['bus', 'okada', 'keke'], returning the word itself. - Change
largestso that it throws an error when it meetsNaNinstead of skipping it.