Math.random method

The Math.random method returns a random fractional number from 0 to 1.

Syntax

javascriptMath.random();

Usage

To obtain a random number in a certain range (fractional or integer), you should use special tricks. Obtaining a random fractional number between min and max goes like this:

javascriptfunction getRandomArbitary(min, max) {
  return Math.random() * (max - min) + min;
}

And now we get a random integer between min and max:

javascriptfunction getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Example

Let's output a random number from 0 to 1:

javascriptconsole.log(Math.random());

The code execution result:

javascript0.5416665468657356

Example

Let's output a random integer from 10 to 100:

javascriptfunction getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandomInt(10, 100));

The code execution result:

javascript12