The JavaScript Math.max() method
The Math.max() method returns the largest of the numbers you pass it. Math.max(3, 8, 5) is 8. It takes separate arguments, not an array — so to find an array's maximum, spread it: Math.max(...numbers). Its opposite is Math.min().
Overview
Math.max() compares the numbers you give it and returns the biggest. The thing to know upfront is that it takes its values as separate arguments, not as an array — Math.max(3, 8, 5), not Math.max([3, 8, 5]). Pass it an array directly and you'll get NaN.
The fix is the spread operator: Math.max(...numbers) spreads the array out into individual arguments, which is the standard way to find the maximum of an array. Combine it with Object.values() to find the largest value in an object, too.
Two gotchas. With no arguments at all, Math.max() returns -Infinity (the identity for max), so guard against empty arrays. And any non-numeric argument makes the whole result NaN. Its mirror, Math.min(), works identically for the smallest value.
Syntax
Math.max(3, 8, 5) // 8
Math.max(...[3, 8, 5]) // 8 (spread an array)
Math.min(3, 8, 5) // 3
Parameters
The Math.max() method accepts the following parameters.
| Parameter | Description |
|---|---|
value1 ... valueN |
The numbers to compare. Pass them as separate arguments — spread an array with ... to use its elements. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const scores = [72, 95, 88, 64];
document.getElementById('out').textContent =
'highest: ' + Math.max(...scores) + '\n' +
'lowest: ' + Math.min(...scores); // highest: 95 / lowest: 64
</script>
Best practices
- Spread arrays into it:
Math.max(...arr)— passing the array directly returnsNaN. - Guard against empty input, since
Math.max()with no arguments returns-Infinity. - Find an object's largest value with
Math.max(...Object.values(obj)). - Use
Math.min()the same way for the smallest value.
Frequently asked questions
How do I find the largest number in an array?
Math.max(): Math.max(...numbers).Why does Math.max() return NaN?
NaN.What does Math.max() return with no arguments?
-Infinity. So check for an empty array before spreading it in.How do I find the smallest number?
Math.min(...numbers), which works exactly like Math.max() but returns the minimum.