JavaScript Math.max() Method



The Math.max() method in JavaScript accepts a set of arguments as parameters, finds the highest numeric value among it, and returns it. If no arguments are provided, -Infinity is returned, indicating that there is no maximum value. If any of the arguments are Not a Number, "NaN" is returned. This can happen even if there are other valid numbers present.

However, we can also pass an array of numbers as an argument to Math.max(), and it will return the maximum value within the array.

Syntax

Following is the syntax of JavaScript Math.max() method −

Math.max(value1, value2, ..., valueN);

Parameters

This method takes in a random number of parameters. The same is described below −

  • value1, value2, ... valueN: These are the numeric values for which we want to find the maximum. We can provide multiple values separated by commas.

Return value

This method returns the largest of the provided numbers.

Example 1

In the following example, we are using the JavaScript Math.max() method to find the maximum among the provided negative numbers −

<html>
<body>
<script>
   let number = Math.max(-5, -15, -25, -55, -100);
   document.write("Largest number:  ", number);
</script>
</body>
</html>

Output

If we execute the above program, the largest number will be "-5".

Example 2

Here, we are finding the maximum among the provided postive numbers −

<html>
<body>
<script>
   let number = Math.max(5, 15, 25, 55, 100);
   document.write("Largest number:  ", number);
</script>
</body>
</html>

Output

As we can see the output, the largest number will be "100".

Example 3

In this example, we are passing the array as an argument to this method −

<html>
<body>
<script>
   let Array = [10, 20, 30, 40, 50, 60, 90];
   let MaxNum = Math.max(...Array);
   document.write("Largest number:  ", MaxNum);
</script>
</body>
</html>

Output

The spread operator will destructure the array and then this method finds the largest number.

Example 4

Here, we are passing string and character arguments to this method −

<html>
<body>
<script>
   let number1 = Math.max("John", 30, 50, 90);
   document.write(number1, "<br>");

   let number2 = Math.max("John", "Smith", "Candice", "Alisa");
   document.write(number2);
</script>
</body>
</html>

Output

If we execute the above program, it returns "NaN" as result.

Example 5

If no arguments are passed to this method, it returns "-Infinity" as result −

<html>
<body>
<script>
   let number = Math.max();
   document.write(number);
</script>
</body>
</html>

Output

As we can see in the output, -Infinity is returned.

Advertisements