JavaScriptNumbers and Math
Math. max()
Returns the largest of the given numbers.
- Returns
- The largest number,
NaN, or-Infinitywith no arguments.
Example
#JavaScript
const scores = [72, 95, 88]
console.log(Math.max(72, 95, 88))
console.log(Math.max(...scores))
console.log(Math.max())Console
95
95
-Infinity
Definition and usage
#The Math.max() function accepts any number of arguments and returns the largest one. If any argument can’t be converted to a number, the result is NaN.
It doesn’t accept an array directly. To find the largest value in an array, spread it out with the spread syntax: Math.max(...scores).
Called with no arguments, it returns -Infinity, which can be surprising with an empty array.
Syntax
#Syntax
Math.max(value1, value2, …)Parameters
#value1…valueN
numbers
The values being compared.
More examples
#JavaScript
const clamp = (value, min, max) => Math.min(Math.max(value, min), max)
console.log(clamp(120, 0, 100))
console.log(clamp(-5, 0, 100))
console.log(clamp(42, 0, 100))Console
100
0
42
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- With an empty array,
Math.max(...[])returns-Infinity. Check the length first. - The
clampfunction withMath.minandMath.maxis handy for limiting progress, volume, or position.
Related entries
#- Math.min()Returns the smallest of the given numbers.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
- Array.prototype.reduce()Reduces the whole array to a single value, such as a sum, an object, or a new array.
Spotted a mistake or missing an example? Write to us.