Sub topic 14
Random Integers in a Range and the Limits of Math.random
This chapter assumes you already know Math.floor and how it differs from Math.round and Math.trunc, which the rounding chapter covered. You should also be able to run JavaScript in a browser console or in Node.js 19 or later, where crypto is available as a global.
What Math.random gives you
Math.random() returns a floating-point number in the half-open range [0, 1). The result can be 0, but it is never 1. You can't seed it, and each engine chooses its own algorithm. V8 uses xorshift128+.
To turn that float into an integer from min to max inclusive, you scale it, shift it, and floor it.
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6)); // e.g. 4
console.log(randomInt(-3, 3)); // e.g. -1The + 1 is what makes max reachable. Without it, Math.random() * (max - min) stays below max - min, so max never appears. The Math.ceil and Math.floor calls guard against fractional bounds like randomInt(0.5, 6.7).
Common errors
| Mistake | Effect |
|---|---|
| Forgetting `+ 1` | `max` is never produced |
| Using `Math.round` instead of `Math.floor` | The two end values come up half as often as the others |
| Using `Math.trunc` with a negative range shifted after rounding | Values near zero are over-represented |
| Using `Math.random` for tokens, passwords, or IDs | The output can be predicted |
The Math.round bias is easy to see in a simulation:
const counts = {};
for (let i = 0; i < 60000; i++) {
const n = Math.round(Math.random() * 5) + 1;
counts[n] = (counts[n] || 0) + 1;
}
console.log(counts);
// Roughly: { 1: 6000, 2: 12000, 3: 12000, 4: 12000, 5: 12000, 6: 6000 }Math.round sends only [0, 0.5) to 1, but it sends [0.5, 1.5) to 2. The first and last values get half-width slices of the range.
When Math.random is the wrong tool
Math.random is fine for games, animations, shuffling demo data, and sampling. It is not cryptographically secure. Someone who sees enough outputs can recover the generator's internal state and predict the values that come next. For session tokens, reset codes, keys, or anything an attacker would want to guess, use the Web Crypto API.
function secureRandomInt(min, max) {
const range = max - min + 1; // must be <= 2 ** 32
const limit = Math.floor(2 ** 32 / range) * range;
const buf = new Uint32Array(1);
do {
crypto.getRandomValues(buf);
} while (buf[0] >= limit);
return min + (buf[0] % range);
}
console.log(secureRandomInt(100000, 999999)); // e.g. 482913In Node.js you can also call require("node:crypto").randomInt(min, max), which does the same job. Its upper bound is exclusive.
Exercise
A teammate writes Math.floor(Math.random() * 10) + 1 to pick a number from 0 to 10 inclusive. What range does it actually produce, and how do you fix it?
Show answer
It produces 1 to 10. The scale factor 10 gives 10 possible values, and + 1 shifts them up by one. For 0 to 10 inclusive there are 11 values, so use Math.floor(Math.random() * 11), or randomInt(0, 10) with the formula above.
Exercise
Why does Math.round(Math.random() * 5) + 1 make 1 and 6 less likely than 2 through 5?
Show answer
Rounding maps only [0, 0.5) to 0 and [4.5, 5) to 5. Each of those intervals is half as wide as the one-unit intervals that map to 1, 2, 3, and 4, so the end values appear about half as often.