Javascript Reference - JavaScript random() Method








The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

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)

Browser Support

random() Yes Yes Yes Yes Yes

Syntax

Math.random();

Parameters

None.





Return Value

A number representing a number from 0 up to but not including 1.

Example

To select a number between 1 and 10:


var num = Math.floor(Math.random() * 10 + 1); 
console.log(num);

The code above generates the following result.

Random in a range

To select a number between 2 and 10:


var num = Math.floor(Math.random() * 9 + 2); 
console.log(num);

The code above generates the following result.

Random value from an array

To select a random item from an array:


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)]; 
console.log(color);

The code above generates the following result.





Example 2

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
  var rand_url = new Array()
  rand_url[0] = "http://www.java2s.com";
  rand_url[1] = "http://www.java2s.com";
  rand_url[2] = "http://www.java2s.com";
  rand_url[3] = "http://www.java2s.com";
  rand_url[4] = "http://www.java2s.com";
<!--from   ww w  .  j  ava 2  s  . co  m-->
  var rand_num = Math.floor(Math.random() * 5);

  document.write("<A HREF='"+rand_url[rand_num]+"'>" + rand_url[rand_num]
      + "</A>");
</script>
</head>
<body>
</body>
</html>

Click to view the demo