Codectionary / Developer documentation / JavaScript

Math.random()

Math.random() returns a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). It is commonly combined with multiplication and Math.floor() to generate random integers within a specific range. It is not cryptographically secure - for security-sensitive randomness, use the Web Crypto API instead.

Syntax

Math.random()

Examples

Basic Random Number

Generating a raw random decimal between 0 and 1.

console.log(Math.random()); // e.g. 0.7234891...
console.log(Math.random()); // a different value each time

Random Integer in a Range

The standard formula for generating a random whole number within bounds.

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

console.log(randomInt(1, 6));   // simulates a dice roll (1-6)
console.log(randomInt(1, 100)); // random number 1-100

Picking a Random Array Element

A common practical use of Math.random().

const colors = ["red", "green", "blue", "yellow"];

function randomChoice(arr) {
  const index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

console.log(randomChoice(colors)); // a random color from the array

Best practices

  • Use the Math.floor(Math.random() * (max - min + 1)) + min formula for inclusive random integers in a range
  • Do not use Math.random() for anything security-related (tokens, passwords, keys) - use crypto.getRandomValues() instead
  • Remember Math.random() never returns exactly 1, so ranges should account for that when calculating maximums
  • Seed-based reproducible randomness is not built in - use a dedicated library if you need deterministic "random" sequences for testing

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation