The max() method finds the maximum value among the specified values and returns it.
Example
max() Syntax
The syntax of the max() method is:
Math.max(number1, number2,...)
Here, max() is a static method. Hence, we are accessing the method using the class name, Math.
max() Parameters
The max() method takes in a random number of parameters:
-
number1/number2/…- values among which the maximum number is to be computed
max() Return Value
The max() method returns:
- the largest value among the given numbers
- NaN (Not a Number) for non-numeric arguments
Example 1: JavaScript Math.max()
In the above example, we have used Math.max() to find the minimum number among:
Math.max(-1,-11,-132)- returns -1Math.max(0.456,135,500)- returns 500
Example 2: Math.max() with Arrays
In the above example, we have created an array named numbers. Notice that we are passing the array as an argument to the Math.max() method.
let minNum = Math.max(...numbers);
Here, ... is the spread operator that destructures the array and passes the array values as arguments to max().
The method then finds the smallest number.
Example 3: Math.max() with Non-Numeric Argument
In the above example, we have used the max() method with the string and character arguments. For both arguments, we get NaN as output.
Recommended readings: