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.
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());
}
Math.random() Is Not SafeMath.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.
Math.round() instead of Math.floor(): Math.round(Math.random() * 10) gives boundary values 0 and 10 only half as often as 1–9, creating biased probabilities.+ 1 for inclusive upper bounds: Math.floor(Math.random() * 6) generates 0 through 5, never 6. Add + 1 for 1–6..sort(() => Math.random() - 0.5): That shortcut produces heavily biased shuffles; use the Fisher-Yates shuffle loop instead.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.
Create a Uint8Array(16), fill it with crypto.getRandomValues(bytes), and map each byte to two hex characters.
sort(() => Math.random() - 0.5)?Fisher-Yates runs in linear O(n) time and gives every permutation an exact equal probability.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.