What is random() in JavaScript?

widget

In JavaScript, random() is a built-in method that is used to return a random number in the range 0 to 1 (with 0 being inclusive and 1 exclusive). The distribution of the generated random numbers is approximately uniform. It does not actually return a whole number. Instead, it returns a floating point (decimal) value.

The random() method can only be invoked through the Math object because it is a function of this object. This means that it can also be referred to as a Math function.

Math.random()

There are no parameters or arguments for this function

The random() function returns a value in the range 0 to 1, where 0 is inclusive and 1 is exclusive.

Generating numbers from 0 to 1

Let’s take an example that describes how to use the random() method in JavaScript.

console.log(Math.random())
//0.3954510201227812
console.log(Math.random())
//0.14764999900801512

The numbers returned will be different for every method call.

Generating numbers in custom ranges

By default, random() returns a floating point value between 0 and 1. However, different ranges of random numbers can easily be generated.

Generating a random number between 0 and a specified number

In this, we want to generate random numbers between 0 and a, where a is the specified number .

Math.random() * a;

In this example, we want to generate random numbers between 0 and 15. To do this, we multiply the result of Math.random() by 15:

var result ;
for (var i = 0; i < 5; i++){
result = Math.random() * 15;
console.log(result)
}

In the code above, we used the random() function inside the for loop to generate 5 random numbers between 0 and 15.

Generating a random number within a range of values

In this, we want to generate random numbers between b and c. To do this, the difference of both numbers is multiplied by the Math.random() and the lesser number is added.

Math.random() * ( c - b) + b
var result ;
var b = 100;
var c = 500;
for (var i = 0; i < 5; i++){
result = Math.random() * (c - b) + b;
console.log(result)
}

In the code above, we used the random() function inside the for loop to generate 5 random numbers between 100 and 500. To achieve this, we assign both numbers to variables b and c.

Application

The random() method has various applications including gaming, text generator, number generator, generative art.

Next you will see a mini dice game that is built using the random() method.

The code for this game can be seen by clicking on other tabs.

Free Resources