i

JavaScript

Random Definition

Math.random():

Math.random() is used to get a random number between 0 and 1. It always returns a number less than 1.

Example:

var randomNumber = Math.random();

The value of randomNumber varies between 0 and 1. It will always be less than 1.

Random Integers:

To generate random integers, Math.random() can be used with Math.floor().

Code:

If you need a random integer from 0 to n,

Math.floor(Math.random() * n+1);

If you need a random integer from 1 to n,

Math.floor(Math.random() * n) + 1;

Example:

var randomNumber = Math.floor(Math.random() * 16);

In the above example, the value of randomNumber will be any integer from 0 to 15.

var randomNumber = Math.floor(Math.random() * 100) + 1;

In the above example, the value of randomNumber will be any integer from 1 to 100.