Javascript Math Reference : max(x,y)
Javascript Math.
As its name indicate Math.max(x,y) returns the maximum of x and y. Take at the following example
<html> <body> <script type="text/javascript"> <!-- /* ******************************************************** Example - Usage of Math.max ******************************************************** */ var x = 15; var y = 20; document.write ("<br /> Max of x and y is : " + Math.max(x,y)); //--> </script> </body> </html> |
Try this example online here .
Math.max may take more than one arguments. In which case, it returns the maximum of the these arguments. Take a look at this example.
<html> <body> <script type="text/javascript"> <!-- /* ******************************************************** Example - Usage of Math.max ******************************************************** */ var x = Math.max(7,2,12,40); // returns 40 var y = Math.max(-77,-2,-12,-40); // returns -2 document.writeln ("<br /> Max of 7,2,12,40 is : " + x +"<br>"); document.writeln ("<br /> Max 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.max ******************************************************** */ var x = [7,2,12,40]; // returns 40 var y = Math.max.apply(null,x); document.writeln ("<br /> Max 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.