JavaScript Math max()

In this tutorial, you will learn about the JavaScript Math.max() method with the help of examples.

The max() method finds the maximum value among the specified values and returns it.

Example

let numbers = Math.max(12, 4, 5, 9, 0, -3);
console.log(numbers); 

// Output:  12

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()

// max() with negative numbers let numbers1 = Math.max(-1, -11, -132);
console.log(numbers1);
// max() with positive numbers let numbers2 = Math.max(0.456, 135, 500);
console.log(numbers2); // Output: // -1 // 500

In the above example, we have used Math.max() to find the minimum number among:

  • Math.max(-1,-11,-132) - returns -1
  • Math.max(0.456,135,500) - returns 500

Example 2: Math.max() with Arrays

let numbers = [4, 1, 2, 55, 9];

// max() with a spread operator let maxNum = Math.max(...numbers);
console.log(maxNum); // Output: 55

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

// max() with the string argument let numbers1 = Math.max("Dwayne", 2, 5, 79);
console.log(numbers1);
// max() with character arguments let maxNum = Math.max('A', 'B', 'C');
console.log(maxNum); // Output: // NaN // NaN

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:

Did you find this article helpful?