Select the largest value
Compare several numeric candidates
JavaScript · Function
Math.max() returns the greatest value among its arguments. It returns -Infinity with no arguments and NaN when any argument is or converts to NaN.
Math.max() compares zero or more numeric arguments and returns the greatest one. Arguments are converted to numbers as needed; if conversion produces NaN for any argument, the result is NaN, while calling it without arguments produces -Infinity.
Math.max()
Math.max(value1)
Math.max(value1, value2)
Math.max(value1, value2, /* …, */ valueN)| Name | Type | Description |
|---|---|---|
value1, …, valueN | number | Zero or more values whose largest numeric value is selected and returned. |
The largest of the supplied values; -Infinity with no arguments, or NaN if any argument is or converts to NaN.
const values = [12, 7, 19, 4];
const largest = Math.max(...values);
console.log(largest); // 19Spread the array into individual arguments so Math.max() can compare the values.
Compare several numeric candidates
Find an array maximum
Process an oversized or dynamically built array
Math.max() returns the largest supplied value. With no arguments, it returns -Infinity; if any argument becomes NaN during numeric conversion, it returns NaN.
Follow-up: What happens with Math.max(3, undefined)? It returns NaN because undefined converts to NaN.
Use Math.max(...array) for a reasonably sized array. The spread syntax turns each element into a separate argument, matching Math.max(value1, value2, ...valueN).
Follow-up: How should a potentially huge array be handled? Iterate through it or use reduce() to avoid argument-count limits.
Math.max() accepts zero or more values, and those values are converted to numbers before comparison. Consequently, numeric strings can participate numerically, but invalid conversions can produce NaN.
Follow-up: What is Math.max("8", 3)? It returns 8 because the string is converted to the number 8.
Math.min()Math.abs()Math.floor()Math.round()Array.prototype.reduce()