Math.random

In this chapter you will learn:

  1. How to use Math random method
  2. How to get a random number in a range
  3. How to get a random value from an array

random() Method

The Math.random() method returns a random number between the 0 and the 1, not including either 0 or 1.

Math.random() output within a certain integer range by using the following formula:

number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)

To select a number between 1 and 10:

<!DOCTYPE html><!--from  j a  va  2  s. c o m-->
<html>
<head>
    <script type="text/javascript">
        var num = Math.floor(Math.random() * 10 + 1); 
        document.writeln(num);

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

Click to view the demo

Random in a range

To select a number between 2 and 10:

<!DOCTYPE html><!--from  ja  v  a  2  s. c  o  m-->
<html>
<head>
    <script type="text/javascript">
        var num = Math.floor(Math.random() * 9 + 2); 
        document.writeln(num);
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Random value from an array

To select a random item from an array:

<!DOCTYPE html><!--   j a va2  s.  c o m-->
<html>
<head>
    <script type="text/javascript">
        function selectFrom(lowerValue, upperValue) {
            var choices = upperValue - lowerValue + 1;
            return Math.floor(Math.random() * choices + lowerValue);
        }    
    
        var colors = ["A", "B", "C", "D", "E", "F", "G"]; 
        var color = colors[selectFrom(0, colors.length-1)]; 
        document.writeln(color);

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

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. What is the array type
  2. Array methods we can use
  3. How to get and set array values
Home » Javascript Tutorial » Math
Math Object
Math min() and max()
Math.ceil()
Math.floor()
Math.round()
Math.random