totn JavaScript

JavaScript: Math max() function

This JavaScript tutorial explains how to use the math function called max() with syntax and examples.

Description

In JavaScript, max() is a function that is used to return the largest value from the numbers provided as parameters. Because the max() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

Syntax

In JavaScript, the syntax for the max() function is:

Math.max([number1, number2, ... number_n]);

Parameters or Arguments

number1, number2, ... number_n
Optional. The numbers that will be evaluated to determine the largest value.

Returns

The max() function returns the largest value from the numbers provided.

If no parameters are provided, the max() function will return -Infinity.

If any of the parameters provided are not numbers, the max() function will return NaN.

Note

  • Math is a placeholder object that contains mathematical functions and constants of which max() is one of these functions.

Example

Let's take a look at an example of how to use the max() function in JavaScript.

For example:

console.log(Math.max(10, 20));
console.log(Math.max(10, 20, 30));
console.log(Math.max(-2, -4, -6, -8));

In this example, we have invoked the max() function using the Math class.

We have written the output of the max() function to the web browser console log, for demonstration purposes, to show what the max() function returns.

The following will be output to the web browser console log:

20
30
-2

In this example, the first output to the console log returned 20 which is the largest of the values 10 and 20.

The second output to the console log returned 30 which is the largest of the values 10, 20 and 30.

The third output to the console log returned -2 which is the largest of the values -2, -4, -6 and -8.

Using the max() function to find the Largest Value in an Array

Finally, we'll take a look at how to use the max() function to find the largest value in an array.

For example:

var totn_array = [5, 10, 15, 20, 25];

console.log(Math.max(...totn_array));

The following will be output to the web browser console log:

25

In this example, the max() method returned 25 which is the largest value from the array called totn_array. This array consisted of 5 elements with the numeric values: 5, 10, 15, 20 and 25.