JavaScript Tutorial JavaScript References

JavaScript - Math.random() Method



The JavaScript Math.random() method returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range.

For generating random number from uniform distribution over [a, b) range, where b>a, the following relationship can be used:

(b-a) * Math.random() + a

The implementation selects the initial seed to the random number generation algorithm. It cannot be chosen or reset by the user.

Syntax

Math.random()

Parameters

No parameter is required.

Return Value

Returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Example:

The example below shows the usage of Math.random() method.

var txt;

//generating a random number from [0,1)
txt = "Random number in [0,1) = " + 
         Math.random() + "<br>";
//generating a random number from [0,10)
txt = txt + "Random number in [0,10) = " + 
         (10*Math.random()) + "<br>";
//generating a random number from [5,10)
txt = txt + "Random number in [5,10) = " + 
         (5*Math.random()+5) + "<br>";
//generating a random number from [-5,10)
txt = txt + "Random number in [-5,10) = " + 
         (15*Math.random()-5) + "<br>";

The output (value of txt) after running above script will be:

Random number in [0,1) = 0.09260976329470672
Random number in [0,10) = 3.598471899689586
Random number in [5,10) = 5.529747793226086
Random number in [-5,10) = -0.6331544169820962

❮ JavaScript - Math Object

5