JavaScript Math max() Method

JavaScript Math max() Method | The JavaScript Math max() method returns the greatest among the given numbers. If no parameters are supplied, then it returns -Infinity and if any one of the parameters cannot be transformed to an integer, the result is NaN.

Since max() is a static method of Basic arithmetic, it is never used as a method of a Math object; rather, it is always used as Math.max().

Syntax:-
Math.max(value1, value2, …)

The following list of parameters, which can be used an unlimited number of times, is accepted by this method:-

  • Value: To discover the largest, this number was provided to the math.max() method.
  • Input values: The largest of the supplied numbers are returned by the Math.max() method.

Example 1:
Input : Math.max(40, 52, 3)
Output: 52

Example 2:
Input : Math.max(-40, -52, -3)
Output: -3

Example 3:
Input : Math.max()
Output: -Infinity

Example 4:
Input : Math.max(40,82,NaN)
Output: NaN

Let us see some JavaScript programs to demonstrate the Math max() method. The JavaScript code below shows how to use the Math max() method.

JavaScript Math max() Method Example

console.log(Math.max(10, 2, 13, 99, -50));

Output:-

99

From the given values:- 10, 2, 13, 99, -50; the 99 is the largest number therefore the JavaScript math.max() return 99.

var max = Math.max(45, 14, 89, 29);
console.log(max);

Output:-

89

Math.max() JavaScript Example with Negative Values

JavaScript Math max() Method Example with Negative values as arguments

console.log(Math.max(-1, -2, -3, -4, -5));

Output:

-1

The program will give us the desired output, which is -1 instead of -5.

JavaScript Math.max() Example with No Arguments

The return value of the Math.min() function is Infinity if no arguments are passed to it. The value given is returned when a single argument is passed to the Math.min() function and the parameter is compared to infinity. Because infinity is always the larger value when we compare any number to it, the number becomes the minimum value.

The return value of the Math.max() function is -Infinity if we don’t offer it any arguments. A single argument supplied to the Math.max() technique compares the parameter to zero and returns the provided value. Due to the fact that -infinity always has the lowest value when any value is compared to it, the number becomes the maximum value.

console.log(Math.max());

Output:-

-Infinity

JS Math.max() Example with NaN

While calling JavaScript Math.max() method if argument contains NaN (Not a Number) then Math.max() method always returns NaN.

console.log(Math.max(-1, -2, -3, NaN));

Output:-

NaN

console.log(Math.max(10, 20, 3, NaN));

Output:-

NaN

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *