The JavaScript Math.random() method
The Math.random() method returns a pseudo-random decimal from 0 (inclusive) up to 1 (exclusive). To get a whole number in a range, scale and floor it: Math.floor(Math.random() * 6) + 1 rolls a 1 to 6. It's not cryptographically secure — for that, use crypto.getRandomValues().
Overview
Math.random() is the starting point for almost all randomness in JavaScript. On its own it gives a floating-point number that's at least 0 and always less than 1 — something like 0.4271. You rarely want that raw value; you want a random integer, a random pick, a random chance.
The pattern for a whole number in a range is worth memorizing: Math.floor(Math.random() * (max - min + 1)) + min. Multiply to scale up the range, Math.floor() to drop the decimals, and add the minimum to shift the start. For a dice roll that's Math.floor(Math.random() * 6) + 1. To pick a random array element, use the array's length as the range and index into it.
One important limitation: Math.random() is pseudo-random and predictable enough that it must never be used for anything security-sensitive — tokens, passwords, shuffling a real-money game. For those, use the cryptographically secure crypto.getRandomValues(). For shuffles, UI variety and casual games, Math.random() is perfect.
Syntax
const r = Math.random() // 0 <= r < 1
// random integer from min to max (inclusive)
Math.floor(Math.random() * (max - min + 1)) + min
// random array element
arr[Math.floor(Math.random() * arr.length)]
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<button onclick="roll()" style="font:14px system-ui;margin-top:8px">Roll the dice</button>
<script>
function roll() {
const die = Math.floor(Math.random() * 6) + 1;
document.getElementById('out').textContent = 'You rolled a ' + die;
}
roll();
</script>
Best practices
- Memorize the integer formula:
Math.floor(Math.random() * (max - min + 1)) + min. - Pick a random array item with
arr[Math.floor(Math.random() * arr.length)]. - Never use
Math.random()for security — tokens, passwords, secrets needcrypto.getRandomValues(). - Use Math.floor() (not
Math.round()) when scaling, to keep the range even.
Frequently asked questions
What range does Math.random() return?
0 (inclusive) up to but not including 1.How do I get a random integer between two numbers?
Math.floor(Math.random() * (max - min + 1)) + min for an inclusive range.How do I pick a random item from an array?
arr[Math.floor(Math.random() * arr.length)].Is Math.random() secure?
crypto.getRandomValues().