JS Random
Math.random() returns a pseudo-random float in [0, 1) — never quite 1. Build the range you need around it.
Recipes
JS
// Random integer in [min, max] inclusive
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Random float in [min, max)
function randFloat(min, max) {
return Math.random() * (max - min) + min;
}
// Pick a random item from an array
const pick = arr => arr[Math.floor(Math.random() * arr.length)];
// Coin flip
const heads = Math.random() < 0.5;
// Shuffle (Fisher–Yates — proper, unbiased)
function shuffle(arr) {
const out = [...arr];
for (let i = out.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[out[i], out[j]] = [out[j], out[i]];
}
return out;
}
When you need real randomness
Math.random() is fine for games, animations, demo IDs. It's not cryptographically secure — don't use it for tokens, passwords, or keys. The Web Crypto API gives proper randomness:
JS
// Cryptographically secure random integer in [0, 2^32) const buf = new Uint32Array(1); crypto.getRandomValues(buf); const secure = buf[0]; // Secure random UUID crypto.randomUUID(); // "0190a0fa-…"
Tip:
arr.sort(() => Math.random() - 0.5) looks like a shuffle but is biased. Use Fisher–Yates above for a fair shuffle.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Random!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Generate a random integer between 1 and 6 (inclusive).
const dice = Math.
(Math.random() * 6) + 1;
Five letters — round down.
Discussion
Loading…