JS Random
JavaScript Random: Generating Safe Ranges and Secure Values
JavaScript Math.random() returns a floating-point number greater than or equal to 0 and strictly less than 1. By scaling and flooring that number, you can simulate dice rolls, pick random array items, or shuffle lists.
Generating Random Integers in a Range
Because Math.random() never equals 1, multiplying by (max - min + 1) and calling Math.floor() produces an even distribution across every integer from min through max inclusive.
// Random integer between min and max (both inclusive)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const diceRoll = randomInt(1, 6);
const colors = ["emerald", "amber", "sky", "rose"];
const pickedColor = colors[randomInt(0, colors.length - 1)];
console.log({ diceRoll, pickedColor });
// Cryptographically secure ID in modern browsers & Node.js
if (typeof crypto !== "undefined" && crypto.randomUUID) {
console.log("Secure UUID:", crypto.randomUUID());
}
When Math.random() Is Not Safe
Math.random() uses a fast pseudorandom generator designed for games, animations, and UI sampling. Never use Math.random() for passwords, session tokens, OTP codes, or API keys because its output can be predicted.
For security-sensitive randomness, always use crypto.getRandomValues() or crypto.randomUUID(), which exist in modern browsers and Node.js.
Common Mistakes to Avoid
- Using
Math.round()instead ofMath.floor():Math.round(Math.random() * 10)gives boundary values0and10only half as often as1–9, creating biased probabilities. - Forgetting
+ 1for inclusive upper bounds:Math.floor(Math.random() * 6)generates0through5, never6. Add+ 1for1–6. - Sorting an array randomly with
.sort(() => Math.random() - 0.5): That shortcut produces heavily biased shuffles; use the Fisher-Yates shuffle loop instead.
Frequently Asked Questions
Can Math.random() ever return 1?
No, the JavaScript specification guarantees Math.random() returns a number in the half-open interval [0, 1), meaning 0 is possible but 1 is never returned.
How do I generate a random hex token securely?
Create a Uint8Array(16), fill it with crypto.getRandomValues(bytes), and map each byte to two hex characters.
Why is Fisher-Yates better than sort(() => Math.random() - 0.5)?
Fisher-Yates runs in linear O(n) time and gives every permutation an exact equal probability.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.