Math min() and max()

In this chapter you will learn:

  1. How to use Math min() and max() methods
  2. How to get the max/min value for an array

Math min() and max() Methods

The min() and max() methods determine which number is the smallest or largest in a group of numbers. These methods accept any number of parameters:

<!DOCTYPE html><!--from  ja v  a2 s  . c o m-->
<html>
<head>
    <script type="text/javascript">

        var max = Math.max(3, 5, 3, 6); 
        document.writeln(max); // 6
    
        var min = Math.min(3, 5, 3, 6); 
        document.writeln(min); //3 

    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Max/Min value for an array

To find the maximum or the minimum value in an array, you can use the apply() method as follows:

<!DOCTYPE html><!--from  j ava 2  s.  co m-->
<html>
<head>
    <script type="text/javascript">
            var values = [1, 2, 3, 4, 5, 6, 7, 8]; 
            var max = Math.max.apply(Math, values); 
            document.writeln(max);//8
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to use Math.ceil()
Home » Javascript Tutorial » Math
Math Object
Math min() and max()
Math.ceil()
Math.floor()
Math.round()
Math.random