JavaScript Math.max(): Find the Maximum Number

JavaScript Math.max(): largest of two or many values, spread with arrays, and how -Infinity and NaN behave.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JavaScript Math.max(): Find the Maximum Number

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

Number line illustrating Math.min Math.max and a clamp pattern

javascript
Math.max(value1, value2, ...valueN)
Output

It returns the largest numeric value. If any argument becomes NaN, the result is NaN.


Method 1: Find Maximum of Two Numbers

javascript
console.log(Math.max(10, 25));
Output

You should see one line logging 25.


Method 2: Find Maximum of Multiple Numbers

javascript
console.log(Math.max(12, 3, 4, 5, 67, 321, 121212));
Output

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.

javascript
const numbers = [3, 9, 2, 14];

console.log(Math.max(...numbers));
Output

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.

javascript
console.log(Math.max());
Output

You should see one line logging -Infinity.

If any argument is NaN, the result is NaN.

javascript
console.log(Math.max(1, NaN, 3));
Output

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.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …