A random decimal
console.log(Math.random()); // e.g. 0.4271...
This is the building block for every other random value. On its own it gives a fractional number below 1.
A random integer in a range
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 6)); // 1 to 6
Multiplying widens the range, Math.floor drops the decimal, and adding min shifts the start point.
Pick a random array item
const colors = ["red", "green", "blue"];
const pick = colors[Math.floor(Math.random() * colors.length)];
console.log(pick);
Multiplying by the array length and flooring gives a valid random index every time.
Cryptographically secure randomness
const arr = new Uint32Array(1);
crypto.getRandomValues(arr);
console.log(arr[0]);
For tokens or anything security-related, use crypto.getRandomValues instead of Math.random.
Common mistakes
- Forgetting the
+ 1. Without it the maximum value is never reached. - Using
Math.roundinstead ofMath.floor. Rounding skews the distribution at the ends. - Using
Math.randomfor security. It is not cryptographically safe.
Frequently asked questions
Is Math.random truly random?
It is pseudo-random and good enough for games and shuffling, but not for security. Use crypto.getRandomValues when randomness must be unpredictable.
How do I get a random number including the maximum?
Add 1 inside the floor: Math.floor(Math.random() * (max - min + 1)) + min makes both ends reachable.
Learn math and logic hands-on in our free JavaScript course.