Javascript Math Reference : Math.min

Javascript Math.min


The Math.min is a counterpart of the Math.min and finds the mininmum of its arguments. If you pass two arguments as in Math.min(x,y) , it returns the mimimum of x and y. Take at the following example

<html>
<body>
<script type="text/javascript">
<!--

/*
********************************************************
Example - Usage of Math.min
********************************************************
*/
var x = 15;
var y = 20;

document.write ("<br /> Max of x and y is : " + Math.min(x,y));

 //-->
</script>
</body>
</html>



Try this example online here .

As in Math.min, Math.max may take more than one arguments. In which case, it returns the miniimum of the these arguments. Take a look at this example.

<html>
<body>
<script type="text/javascript">
<!--

/*
********************************************************
Example - Usage of Math.min
********************************************************
*/

var x = Math.min(7,2,12,40); // returns 2
var y = Math.min(-77,-2,-12,-40); // returns -77


document.writeln ("<br /> Min of 7,2,12,40 is : " + x +"<br>");
document.writeln ("<br /> Min of -77,-2,-12,-40 is : " + y +"<br>");

 //-->
</script>
</body>
</html>



Try this example online here .


Take note of how negative numbers are treated.
What if you wish to find the maximum of a list of numbers stored in array ? You make use of the Javascript apply and pass the array in it. Take a look at the following example


<html>
<body>
<script type="text/javascript">
<!--

/*
********************************************************
Example - Usage of Math.min for array using apply
********************************************************
*/

var x = [7,2,12,40]; 
var y = Math.min.apply(null,x);
document.writeln ("<br /> min of 7,2,12,40 is : " + y +"<br>");

 //-->
</script>
</body>
</html>



Try this example online here .



The use of the Array and apply method also turns out to be much faster than the for loop method for large arrays.