Javascript Math.max() is used to find the largest or max number among a series of numbers. max() accepts variable number of arguments.
This means that you can pass any number of arguments to max().
As per official MDN docs,

The Math.max() function returns the largest of the zero or more numbers given as input parameters.

Syntax of max() function is

max(num1, num2, num3, …..)

max() is a static function and belongs to javascript Math object and that is why it is invoked as Math.max().
max() return values
max() returns different value as per the arguments passed to it.
1. Maximum value when more than one numbers are passed.
2. NaN when an argument cannot be converted to a number such as a string.
3. -Infinity when no arguments are passed.
max() examples
Following are some of the usage examples of max() with different input arguments.

let max = Math.max(12,56,9,0,35);
console.log('Max with all positive numbers: ' + max);

max = Math.max(-12,-56,-9,-1,-35);
console.log('Max with all negative numbers: ' + max);

max = Math.max(12,56,9,0,'a');
console.log('Max with one invalid argument: ' + max);

max = Math.max();
console.log('Max with no arguments: ' + max);

This prints

Max with all positive numbers: 56
Max with all negative numbers: -1
Max with one invalid argument: NaN
Max with no arguments: -Infinity

In case of negative numbers, max() returns the number having smallest numeric value.

max() with arrays
Math.max() can be used to find maximum element of a javascript array. But you cannot directly pass an array as argument to max() as it will return NaN.
For using array with max(), you need to destructure it using javascript spread operator, which extracts individual elements from the array.
spread operator is used by placing three dots() before the array

const arr = [12,56,9,0,35]
let max = Math.max(...arr);
console.log('Max with an array: ' + max);

which prints

Max with an array: 56

As with numbers, if the array contains an element that cannot be converted to a number, then the result is NaN.
Also, if the array is empty, the max() will return -Infinity.
Browser Compatibility
Below is the compatibility table of Math.max() for different browser versions.


Hope the article was helpful.

Liked the article ? Spread the word...

Leave a Reply