JavaScript Math random()

The Math.random() function returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Example


Math.random() Syntax

The syntax of the Math.random() function is:

Math.random()

random, being a static method, is called using the Math class name.


Math.random() Parameters

The Math.random() function does not take in any parameters.


Math.random() Return Value

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

Example 1: Using Math.random()

Output

0.5856407221615856

Note: You might get a different output in the above program as Math.random() will generate a random number.


Example 2: Generate random number between two numbers

Output

6.670210050278422
70.46845725092274

Here, we can see that the random value produced by Math.random() is scaled by a factor of the difference of the numbers.

Then it is added to the smaller number to produce a random number between the given range.


Example 3: Generate random integer between two numbers

Output

6
46

Firstly, we ceil the min value while floor the max value.

Here, we can see that the random value produced by Math.random() is scaled by a factor of the difference of the numbers.

Then it is floored using Math.floor() to make it an integer. Finally, it is added to the smaller number to produce a random number between the given range.


Example 4: Generate integer between two numbers(inclusive)

Output

8
100

Firstly, we ceil the min value while floor the max value.

In this case, the only difference is that one is added to the difference so that the max value is also included.