JavaScript Random Numbers

Math.random() is JavaScript's built-in way to generate pseudo-random numbers. It returns a floating-point number between 0 (inclusive) and 1 (exclusive). For security-sensitive applications, use crypto.getRandomValues() instead.

Math.random() Basics

Math.random() returns a number >= 0 and < 1. Each call produces a different pseudo-random number. It takes no arguments.

Math.random()
// Basic random number (0 to 0.999...)
console.log("Random:", Math.random());
console.log("Random:", Math.random());
console.log("Random:", Math.random());

// Random * 10 gives 0 to 9.999...
console.log("Random * 10:", Math.random() * 10);

// Random * 100 gives 0 to 99.999...
console.log("Random * 100:", Math.random() * 100);

Random Integers

To get random integers, multiply Math.random() by a range and use Math.floor() to round down. Be careful about whether the bounds are inclusive or exclusive.

Random Integers
// Random integer from 0 to 9
const rand0to9 = Math.floor(Math.random() * 10);
console.log("0-9:", rand0to9);

// Random integer from 1 to 10
const rand1to10 = Math.floor(Math.random() * 10) + 1;
console.log("1-10:", rand1to10);

// Random integer from 0 to 100
const rand0to100 = Math.floor(Math.random() * 101);
console.log("0-100:", rand0to100);

// Reusable function: random int in range [min, max]
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log("1-6 (dice):", randomInt(1, 6));
console.log("10-20:", randomInt(10, 20));
console.log("100-999:", randomInt(100, 999));
📝 Note: The formula for a random integer between min and max (both inclusive) is: Math.floor(Math.random() * (max - min + 1)) + min. This is worth memorizing!

Random Range (Floats)

To get random floating-point numbers in a specific range, multiply and add without flooring.

Random Float Range
// Random float between min and max
function randomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

console.log("1.0-5.0:", randomFloat(1, 5).toFixed(2));
console.log("-10 to 10:", randomFloat(-10, 10).toFixed(2));

// Random percentage
const pct = (Math.random() * 100).toFixed(1);
console.log("Random %:", pct + "%");

// Random color value (0-255)
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
console.log(`Random RGB: rgb(${r}, ${g}, ${b})`);

Random from Array

A very common pattern is picking a random element from an array. Use Math.random() with the array length to get a random index.

Random from Array
// Pick random element
function randomFrom(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

const colors = ["Red", "Green", "Blue", "Yellow", "Purple"];
console.log("Random color:", randomFrom(colors));
console.log("Random color:", randomFrom(colors));

// Shuffle an array (Fisher-Yates algorithm)
function shuffle(arr) {
  const result = [...arr];
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Shuffled:", shuffle(nums));
console.log("Original:", nums);

// Random boolean
const coinFlip = Math.random() < 0.5;
console.log("Coin flip:", coinFlip ? "Heads" : "Tails");

Cryptographic Randomness

Math.random() is NOT cryptographically secure. For security-sensitive operations like generating tokens, passwords, or encryption keys, use crypto.getRandomValues() or crypto.randomUUID().

Secure Random Numbers
// crypto.getRandomValues() - secure random integers
const secureArray = new Uint32Array(5);
crypto.getRandomValues(secureArray);
console.log("Secure randoms:", [...secureArray]);

// Secure random number 0-99
const secureRand = new Uint32Array(1);
crypto.getRandomValues(secureRand);
console.log("Secure 0-99:", secureRand[0] % 100);

// Generate UUID
const uuid = crypto.randomUUID();
console.log("UUID:", uuid);

// Generate random hex string
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
const hex = [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');
console.log("Random hex:", hex);
MethodRangeUse Case
Math.random()0 to <1 (float)General random numbers
Math.floor(Math.random() * n)0 to n-1 (int)Random index
Math.floor(Math.random() * (max-min+1)) + minmin to max (int)Random in range
crypto.getRandomValues()Depends on TypedArraySecurity-sensitive
crypto.randomUUID()UUID v4 stringUnique identifiers
Exercise:
What is the correct formula for a random integer between 1 and 10 (inclusive)?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.