Javascript - Math random Number


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

You can use Math.random() to select numbers 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:

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

To select a number between 2 and 10:

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

There are only nine numbers when counting from 2 to 10, so the total number of choices is nine, with the first possible value being 2.

The following code uses a function that handles the calculation of the total number of choices:


function selectFrom(lowerValue, upperValue) {
    var choices = upperValue - lowerValue + 1;
    return Math.floor(Math.random() * choices + lowerValue);

var num = selectFrom(2,10);
console.log(num);  //number between 2 and 10, inclusive


Here, the function selectFrom() accepts two arguments: the lowest value and the highest value.

To select a random item from an array:

var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown",""];
var color = colors[selectFrom(0, colors.length-1)];

In this example, the second argument to selectFrom() is the length of the array minus 1, which is the last position in an array.