offline version v3


31 of 264 menu

Math.random method

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

Syntax

Math.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:

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

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

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

Example

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

console.log(Math.random());

The code execution result:

0.5416665468657356

Example

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

function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandomInt(10, 100));

The code execution result:

12
enru