Skip to content
Tutorials Center
My learning

Topics

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).

JavaScript
Math.max(3, 9, 4);          // 9
Math.max(...[3, 9, 4]);     // 9

Try it

JS Largest value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS NaN, coercion, clamping and zeros

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 a RangeError. Use a for loop or reduce() for big data.
  • One bad value poisons the result. A single NaN makes everything NaN. Filter first: Math.max(...values.filter(Number.isFinite)).
  • Coercion happens quietly. Numeric strings work, null becomes 0, undefined becomes NaN, and a one-item array like [4] converts to 4.
  • 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, because Math.max only returns the number, not the item.
  • Clamping: pair it with Math.min() as shown. The modern CSS clamp() 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 in new 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.