/

HTML / CSS / JavaScript Tutorial

JavaScript Math method: max()

[this page | pdf | back links]

The max() method (of the Math object) returns the maximum of a set of real numbers.

 

It has the following syntax with the following parameters:

 

Math.max(x1, x2, x3, …)

 

Parameter

Required / Optional

Description

x1, x2, x3, …

Required

Input values

 

You can find the maximum of an array using a format such as:

 

Math.max.apply(null, xarray)

 

since e.g. Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3)

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value</th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var c1 = 4.3;
var c2 = 2.2;
var c3 = 3.8;
var x = Math.max(c1,c2,c3);
var d = [c1,c2,c3];
var y = Math.max.apply(null,d);
document.getElementById("Example").innerHTML =
  'var c1 = 4.3;<br>var c2 = 2.2;<br>var c3 = 3.8;<br>' +
  'var x = Math.max(c1 , c2 , c3 )<br>' +
  'var d = [c1, c2, c3];<br>' +
  'var y = Math.max.apply(null, d);<br>'
document.getElementById("Result").innerHTML
  = 'x = ' + x + '<br>' +
    'y = ' + y;
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodMathMax() {
  var z = 12.5; return !!Math.max(z);
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Numbers and Math


Desktop view | Switch to Mobile