JavaScript Math max() Method

The JavaScript Math max() method evaluates two or more numbers and returns the largest number among them.

Syntax

Math.max(x, y, z, ...)

Parameters

x, y, z,…: The numbers out of which the maximum is to be determined. You can pass any number of arguments.

Return Value

The maximum of all the parameters passed.

  1. If no argument is passed, this method returns negative infinity(-Infinity).
  2. If any argument is not a number and can’t be converted into one, this method returns NaN.
  3. If the parameter is null, it returns 0.
  4. If a parameter is an empty string, it returns 0.

Visual Representation Visual Representation of JavaScript Math max() Method

Example 1: How to Use Math max() Method

console.log(Math.max(25, 50));
console.log(Math.max(25, 50, 75));
console.log(Math.max(-25, 25, 50, -50));
console.log(Math.max(-25, -50, -75));

Output

50
75
50
-25

Example 2: No parametersVisual Representation of No parameters

console.log(Math.max());

Output

-Infinity

Example 3: Handling Non-Numeric Values

var a = "JavaScript"; // non-numeric string
var b = [25, 50, 74, 100]; // array with more than one element
var c; // undefined variable
var d = {}; // empty object

console.log(Math.max(a, 1));
console.log(Math.max(...b));
console.log(Math.max(c, 3));
console.log(Math.max(d, 4));


var e = "23"; // numeric string
var f = [10]; // array with a single element

console.log(Math.max(e, 5));
console.log(Math.max(f, 1));

Output

NaN
100
3
NaN
23
10

Browser compatibility

  1. Chrome 1 and above
  2. Edge 12 and above
  3. Firefox 1 and above
  4. Safari 1 and above
  5. Opera 4 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.