Math.max()

Returns the largest of the given numbers.

Returns
The largest number, NaN, or -Infinity with no arguments.
On this page

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

#
Clamping a value to a range
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 clamp function with Math.min and Math.max is handy for limiting progress, volume, or position.

Related entries

#

Spotted a mistake or missing an example? Write to us.