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 timeRandom 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-100Picking 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 arrayBest 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
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification