pink three pointed crown logo

StyleKing.biz

StyleKing.biz

JavaScript Math.random

The Math.random() method returns a pseudo-random floating-point number.

Description

The random() static method of the Math object returns a pseudo-random floating-point number that’s greater than or equal to 0 and less than 1.

For a usable implementation of getting a larger random number see below.

Return Type

A Number.

Warnings

This method is NOT cryptographically secure. If you need cryptographically secure random numbers use Crypto.getRandomValues() instead.

Examples

// Sample JavaScript
Math.random(); // a number 0 <= 1 eg. 0.14737912887430982

Random Number in a Range

// Sample JavaScript
let max = 100;
Math.floor( Math.random() * max ); // a number between 0 and 100 eg. 42

function randomInt(max) {
  Math.floor( Math.random() * max ); // a number between 0 and max
}

function randomRange(min, max) {
  Math.floor( Math.random() * (max - min + 1) ) + min; // a number between min and max
}

Full Developer Reference

Attribution