JavaScript Math.random()
Syntax & Examples


Math.random() static-method

The Math.random() method in JavaScript returns a pseudo-random number between 0 (inclusive) and 1 (exclusive). It is commonly used to generate random numbers for various purposes, such as simulations, games, or random sampling. It is a static method of Math, meaning it is always used as Math.random() and not as a method of a Math object created (Math is not a constructor).


Syntax of Math.random()

The syntax of Math.random() static-method is:

Math.random()

This random() static-method of Math returns a pseudo-random number between 0 and 1.

Return Type

Math.random() returns value of type Number.



✐ Examples

1 Using Math.random() to generate a random number

In this example, we use the Math.random() method to generate a random number between 0 and 1.

For example,

  1. We call Math.random() with no arguments.
  2. The method returns a pseudo-random number between 0 and 1.
  3. We log the result to the console using console.log().

JavaScript Program

console.log(Math.random());

Output

A random number between 0 and 1 (e.g., 0.567890123456789)

2 Using Math.random() to generate a random integer between 0 and 10

In this example, we use the Math.random() method to generate a random integer between 0 and 10.

For example,

  1. We call Math.random() to generate a random number between 0 and 1.
  2. We multiply the result by 11 to get a range from 0 to 10.999...
  3. We use Math.floor() to round down to the nearest integer.
  4. We log the result to the console using console.log().

JavaScript Program

console.log(Math.floor(Math.random() * 11));

Output

A random integer between 0 and 10 (e.g., 7)

3 Using Math.random() to generate a random decimal between 1 and 100

In this example, we use the Math.random() method to generate a random decimal number between 1 and 100.

For example,

  1. We call Math.random() to generate a random number between 0 and 1.
  2. We multiply the result by 100 to get a range from 0 to 99.999...
  3. We add 1 to shift the range to 1 to 100.999...
  4. We log the result to the console using console.log().

JavaScript Program

console.log(Math.random() * 100 + 1);

Output

A random decimal number between 1 and 100 (e.g., 42.7890123456789)

Summary

In this JavaScript tutorial, we learned about random() static-method of Math: the syntax and few working examples with output and detailed explanation for each example.