SnippetJavaScript
Random integer in a range
An inclusive-bounds random integer helper built on Math.random, with a note on why it's unsuitable for anything security-sensitive.
Last updated
Snippetjavascript
function randomInt(min, max) {
const lo = Math.ceil(min);
const hi = Math.floor(max);
return lo + Math.floor(Math.random() * (hi - lo + 1));
}
// randomInt(1, 6) -> an integer from 1 to 6, inclusive, like a die rollHow it works
Math.random() alone returns a float in [0, 1), so getting a usable integer means scaling and flooring it: multiplying by (hi - lo + 1) and flooring spreads the result evenly across every whole number from 0 to hi - lo, and adding lo shifts that range up to start at lo instead of 0. The +1 is what makes max INCLUSIVE — leaving it off would make max reachable in the float but never as a floored integer.
Math.ceil(min) and Math.floor(max) guard against non-integer bounds: pass randomInt(1.5, 6.5) and you still get a clean integer between 2 and 6, rather than a fractional edge leaking into the result.
Edge cases to know
- →Math.random() is NOT cryptographically secure — its output is predictable enough to reconstruct in some engines. Never use this for tokens, passwords, or anything security-sensitive; use crypto.getRandomValues() (browser and Node) for that instead.
- →If min > max after the ceil/floor adjustment, hi - lo + 1 goes negative and the function returns NaN — validate the order of your bounds upstream if they're not both hard-coded.
- →The distribution is uniform enough for games and sampling, but Math.random()'s underlying PRNG quality varies by engine — not a concern for typical UI use, but worth knowing if you're doing anything statistical.