Non-security random integers
Choose an array index or generate a bounded integer for simulations and games.
JavaScript · Function
Math.random() returns an approximately uniformly distributed pseudo-random floating-point number from 0 inclusive to 1 exclusive. It accepts no arguments and is not suitable for cryptographic security.
Calling Math.random() produces a pseudo-random floating-point value in the interval from 0, inclusive, to 1, exclusive. Multiply it by a range width to scale the interval, then use Math.floor() when an integer is required.
Math.random()A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
function randomInt(max) {
return Math.floor(Math.random() * max);
}
console.log(randomInt(3)); // 0, 1, or 2Scales the returned value to a range and floors it to produce an integer from 0 through max - 1.
Choose an array index or generate a bounded integer for simulations and games.
Create a fractional value within an application-defined numeric interval.
Vary visual effects, test data, or randomized UI behavior where unpredictability is not a security requirement.
It returns a pseudo-random floating-point number greater than or equal to 0 and less than 1. The distribution is approximately uniform over that interval.
Follow-up: How would you produce an integer from 0 through 9? Multiply by 10 and apply Math.floor(), yielding Math.floor(Math.random() * 10).
Use Math.random() * (max - min) + min for a floating-point value in the interval [min, max). The lower bound may be returned, while the upper bound is excluded.
Follow-up: How would you include an integer upper bound? Use Math.floor(Math.random() * (max - min + 1)) + min for integer bounds.
No arguments are accepted. The function's pseudo-random output is not cryptographically secure, so security-sensitive randomness should come from Crypto.getRandomValues().
Follow-up: Why not seed Math.random() yourself? Its initial seed is selected by the implementation and cannot be chosen or reset by the user.
Math.floor()Crypto.getRandomValues()Math