JavaScript Math.max() returns the largest of the numeric arguments you pass in. Pass numbers directly, or spread an array when every candidate is already collected—for example Math.max(...scores). Remember that Math.max() with no arguments yields -Infinity, so guard empty arrays in application code. The companion API for the smallest value is JavaScript Math.min().
Environment: Node.js v20.18.2. Each snippet is plain JavaScript; the line after it states the expected console output.
Math.max Syntax
Math.max(value1, value2, ...valueN)It returns the largest numeric value. If any argument becomes NaN, the result is NaN.
Method 1: Find Maximum of Two Numbers
console.log(Math.max(10, 25));You should see one line logging 25.
Method 2: Find Maximum of Multiple Numbers
console.log(Math.max(12, 3, 4, 5, 67, 321, 121212));You should see one line logging 121212.
Method 3: Find Maximum Value in an Array
Math.max() expects separate arguments, not one array. Use spread syntax to expand an array into arguments.
const numbers = [3, 9, 2, 14];
console.log(Math.max(...numbers));You should see one line logging 14.
For very large arrays, a loop or reduce() can avoid spreading too many arguments.
Method 4: Handle Empty Input and NaN
Calling Math.max() with no arguments returns -Infinity.
console.log(Math.max());You should see one line logging -Infinity.
If any argument is NaN, the result is NaN.
console.log(Math.max(1, NaN, 3));You should see one line logging NaN.
Common Questions About Math.max
How do I get max of two numbers in JavaScript?
Use Math.max(a, b). For example, Math.max(10, 25) returns 25.
How do I use Math.max with an array?
Use spread syntax: Math.max(...numbers).
Why does Math.max return -Infinity?
Math.max() returns -Infinity when called with no arguments.
Summary
Math.max picks the largest argument; spread arrays (Math.max(...arr)) and watch for NaN (poisons the result) and empty calls (-Infinity).
JavaScript Math.max() returns the largest number from its arguments. Use it directly for two or more numbers, and use spread syntax for arrays. Remember that no arguments return -Infinity, and any NaN argument makes the result NaN.
