Randomization using Math.random()
Files in this demo
├─ index.html └─ script.js
Math.random() gives you a decimal between 0 and 1. That’s the only random function JavaScript has ~ everything else is built out of it.
Math.random() // 0.7263849...
It never returns exactly 1, which matters more than you’d think.
A whole number in a range
Math.floor(Math.random() * 10) // 0 to 9
Multiply to set the range, then Math.floor() to chop off the decimal. Note that * 10 gives you 0 to 9, not 1 to 10.
For a range with both ends included:
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
The + 1 is what makes max reachable. Without it you can never roll a six, and you won’t notice for ages.
A random item from a list
function pick(list) {
return list[Math.floor(Math.random() * list.length)];
}
This is the one I actually use. Random colour, random fortune, random layout ~ all the same three lines.
Not really random
Math.random() is pseudorandom: predictable if you know enough about it. Completely fine for a fortune generator or a colour picker. Not fine for passwords or anything involving security ~ that needs crypto.getRandomValues().
Click to resume
Use the console below.