JavaScript Tutorial
JavaScript Random
Math.random() is a float from 0 up to but not including 1. Scale it to pick an integer in a range.
A float in [0, 1)
Math.random() returns a number greater than or equal to 0 and strictly less than 1. You never get 1. Each call is a new value. There is no seed you set in ordinary browser JavaScript.
The raw value is rarely what you show a user. You multiply, then Math.floor, to land on an integer.
Click Run several times in /javascript/try. The number should change. This
See the raw value
Log a few calls. Every result should sit in that half-open interval. If you need a percentage, multiply by 100. You can still get 0. You will not get 100 from Math.random() * 100 without rounding up.
Example
const r = Math.random();
console.log(r);
console.log(r >= 0);
console.log(r < 1);
document.body.textContent = String(r);
Integers from 0 to n minus one
Math.floor(Math.random() * n) yields 0, 1, …, n − 1. That is the formula for a random index into an array of length n.
Because Math.random() never returns 1, Math.random() * 5 never reaches 5, sofloor never yields 5. You get 0 through 4.
Example
const die = Math.floor(Math.random() * 6) + 1;
console.log(die);
const index = Math.floor(Math.random() * 4);
console.log(index);
document.body.textContent = "die " + die + " / index " + index;
Any integer from min to max
Inclusive range: multiply by how many integers sit in the range, floor, then add min. The count is max - min + 1. For 10 through 20 that count is 11.
Example
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const n = randomInt(10, 20);
console.log(n);
console.log(n >= 10);
console.log(n <= 20);
document.body.textContent = String(n);
Pick an item from a list
A random index is Math.floor(Math.random() * list.length). Use that index with bracket notation. An empty list has length 0; do not pick from it.
Example
const colors = ["red", "green", "blue", "gold"];
const i = Math.floor(Math.random() * colors.length);
const pick = colors[i];
console.log(i);
console.log(pick);
document.body.textContent = pick;
Not for secrets
| Need | Formula |
|---|---|
| Float in [0, 1) | Math.random() |
| Integer 0 … n−1 | Math.floor(Math.random() * n) |
| Integer min … max | Math.floor(Math.random() * (max - min + 1)) + min |
| Random array item | The 0 … n−1 formula as an index |
Math.random is fine for games, shuffle-the-quote widgets, and demos. It is not a cryptographic source. Do not use it for tokens, reset codes, or anything an attacker should not guess.
What to remember
- The raw call is a float from 0 up to but not including 1.
- Scale with multiply, then
Math.floor, for integers. - A die from 1 to 6 is
floor(random * 6) + 1. - Use a random index to pick from an array.
Next: booleans — true, false, and what counts as truthy in an if test.