JavaScript — Random
The one random function
Math.random(); // 0 ≤ x < 1 — e.g. 0.7234982…
Never 1, always ≥ 0, uniform spread. Everything else builds from it.
Ranges
// any float between min and max
function randFloat(min, max) {
return Math.random() * (max - min) + min;
}
randFloat(1.5, 3.5); // e.g. 2.71…
Random integers — the formula to memorize
// integer from min to max INCLUSIVE
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randInt(1, 6); // dice roll 🎲
randInt(0, 255); // byte value
Why floor? Math.round makes edge values half as likely — subtle bias bugs live there.
Classic recipes
Math.floor(Math.random() * 10); // 0–9 digit
Math.random().toString(36).slice(2, 8); // "k7x2p9" id-ish token
Picking from arrays
const colors = ["red", "teal", "gold", "plum"];
colors[Math.floor(Math.random() * colors.length)];
Wrap it:
const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
pick(colors);
Shuffling — carefully
The naive sort-shuffle is biased:
arr.sort(() => Math.random() - 0.5); // ❌ uneven distribution
Correct Fisher–Yates:
function shuffle(arr) {
const a = [...arr]; // don't mutate original
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]]; // swap
}
return a;
}
(Every ordering equally likely — the algorithm card games and quiz apps rely on.)
Coin flips & weighted choices
Math.random() < 0.5 ? "heads" : "tails";
// 70% chance to trigger:
Math.random() < 0.7 && trigger();
Weighted pick by cumulative bands:
function weighted(items) { // [{value, weight}…]
const total = items.reduce((s, i) => s + i.weight, 0);
let roll = Math.random() * total;
for (const item of items) {
roll -= item.weight;
if (roll < 0) return item.value;
}
}
weighted([{value:"rare", weight:5}, {value:"common", weight:95}]);
Security note
Math.random is not cryptographic. Passwords/tokens need:
crypto.randomUUID(); // modern unique ID
crypto.getRandomValues(new Uint8Array(16));
Game dice → Math.random; anything adversarial → crypto.
Mini Practice
- Dice roller: two randInt(1,6), sum them, loop 600× and tally face counts
- Random hex color:
#+ six chars from "0123456789abcdef" - Pick three unique names from an array (shuffle then slice)
- Build a 90/10 rare-drop simulator; verify ratio over 1000 runs
- Compare naive vs Fisher–Yates bias over 100k shuffles of [1,2,3]
Next: math → (already covered inside numbers)
Related Topics
Frequently Asked Questions about Random
What is Random in JavaScript?
Random is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Random?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Random.
Why is Random important in JavaScript?
Random is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.