JavaScript Math.max()

Last Updated on 05 August 2020

To find the largest value from numbers with JavaScript, we use JavaScript Math.max(). The Math.max() is a static function, if everything is fine it will return the largest value from the numbers. If you didn’t pass any parameters, it will return -Infinity. If you pass any of the parameter is not a number or cannot be converted to a number, it will return NaN.

Return Value

  • Largest value : If everything is fine, it will return the largest value from the numbers.
  • NaN : If any of the parameter is not a number or cannot be converted to a number, it will return NaN.
  • -Infinity : If none parameters.

Example

Return largest value from numbers:

Math.max(1, 5, 15, -15); // 15  

Find the largest value from array.

🙅‍♂️🙅‍♂️🙅‍♂️
Math.max([1, 3, 6]); // NaN

👍👍👍
const myArray = [1, 3, 6];
Math.max(...myArray); // 1

If none parameter, it will return -infinity.

Math.max(); // -Infinity  

Syntax

Math.max(number1, number2, ..., numberX)

Parameters

n1, n2, ..., nX – Passing one or more numbers to compare and return the largest value.

More Example

Math.max(32, 10, 213); // 213
Math.max(0, -5, 3, -51, 390, 294); // 390
Math.max(-10, -100, 2, -800 ); // 2
Math.max(5, 15, -3.23); // 15
Math.max(-1.5, -2.3, -1.6); // -1.5

const myArray1 = [1, 3, 6];
const myArray2 = [50, -33, 6.52];
Math.max(...myArray1, -5, 2, ...myArray2, 3.21 ); // 50

Browser Support

BrowserChromeEdgeMozillaSafariOpera
Math.max()YesYesYesYesYes

Leave a Comment