JavaScript Reference ยท Math
Math.max() method
Reference for JavaScript Math.max(): find the largest number from arguments or an array with spread, empty input, NaN behavior, clamping and large arrays.
Math.max() takes any number of arguments and returns the largest one. Every argument is converted to a number first. Called with no arguments it returns -Infinity, and if any argument is NaN (or cannot be converted to a number), the result is NaN.
The method does not accept an array directly. To find the largest value in an array, spread the array into the call: Math.max(...numbers).
Math.max(3, 9, 4); // 9 Math.max(...[3, 9, 4]); // 9
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Math.max() Math.max(value1) Math.max(value1, value2) Math.max(value1, value2, /* โฆ, */ valueN)
| Name | Description |
|---|---|
value1, โฆ, valueN |
Zero or more values. Each is converted to a number. |
Return value: the largest of the given numbers; -Infinity if there are no arguments; NaN if any argument is NaN or converts to it.
Exceptions: a TypeError if any argument is a BigInt or a Symbol. Mixing BigInts is not supported; compare them with > instead.
Usage notes
- Use spread for arrays:
Math.max(...array). An empty array gives-Infinity, which is an easy bug when the list can be empty. - Very large arrays can fail. Spread and
apply()put every element on the call stack, so an array with hundreds of thousands of items may throw aRangeError. Use aforloop orreduce()for big data. - One bad value poisons the result. A single
NaNmakes everythingNaN. Filter first:Math.max(...values.filter(Number.isFinite)). - Coercion happens quietly. Numeric strings work,
nullbecomes0,undefinedbecomesNaN, and a one-item array like[4]converts to4. - Zero signs:
Math.max(-0, 0)is+0. - Not for objects. To find the item with the largest property, use
reduce()or sort a copy, becauseMath.maxonly returns the number, not the item. - Clamping: pair it with
Math.min()as shown. The modern CSSclamp()has no JavaScript twin built in. - Dates:
Math.max(...dates)works, because dates convert to timestamps, but the result is a number, so wrap it innew Date(...).
Browser support
Math.max() is available in every browser and JavaScript runtime. Spread syntax in calls needs a browser from the ES2015 era or later.
Related
Math.min(),Math.abs(),Math.sign(),Array.prototype.reduce()- Lessons: Math, Arrays