JavaScript: How to get the largest number in an array using Math.max( )

If we want the largest one number in an array, we can get that using JavaScript’s  Math.max() function. Simply place the array of values (without square brackets) into the parenthesis of the function. Like so:

console.log(Math.max(1, -5, 2, 8, 17, 0, -2));

Which yields:

17

A list of all negative numbers:

console.log(Math.max(-11, -8, -2));

Which yields:

-2

Notice that the square brackets are removed and the array is placed directly in the parenthesis. If we use the square array brackets, the function will return NaN. For example:

console.log(Math.max([1, -5, 2, 8, 17, 0, -2]));

Strangely, in order to get the max value of 17 in this last example, we have to prepend the array with three ellipsis … ! For example, this works without returning NaN:

console.log(Math.max(...[1, -5, 2, 8, 17, 0, -2]));

Of course, we can also assign the array to a variable and use that as an argument to Math.max(), but we should not forget the three dots before the variable name! For example:

let list = [1, -5, 12, 2, 8, 17, 0, -2];
console.log(Math.max(...list));

 

Note: The three ellipsis in the example above is actually a new JavaScript feature called “spread sytax”. Here is what developer.mozilla.org says about spread syntax:

The new spread operator is a shorter way of writing the apply solution to get the maximum of an array. … However, both spread (…) and apply will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. See Using apply and built-in functions for more details. The reduce solution does not have this problem.

Here is an example of how to use Array.reduce() to get the largest number in a numeric array:

let list = [1, -5, 12, 2, 8, 17, 0, -2];
var max = list.reduce(function(a, b) {
    return Math.max(a, b);
});

For more information about Math.max() see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

For more information about spread syntax, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

For more information about Array.reduce() see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce