Generate a random number between two numbers in JavaScript
By Flavio Copes
Learn how to generate a random number between two values in JavaScript by combining Math.random() and Math.floor(), for example to pick a number from 1 to 6.
To generate a random integer between two numbers in JavaScript, use a combination of Math.floor() and Math.random().
This one line of code will return a number between 1 and 6 (both included):
Math.floor(Math.random() * 6 + 1)
There are 6 possible outcomes here: 1, 2, 3, 4, 5, 6. A perfect dice roll.
How does it work?
Math.random() returns a floating point number between 0 (included) and 1 (excluded). It can return 0, but it never returns exactly 1.
Multiplying by 6 gives us a number between 0 and 5.999… Adding 1 shifts that to between 1 and 6.999… Then Math.floor() cuts off the decimal part, leaving an integer from 1 to 6.
Each of the 6 values gets the same slice of the 0–1 range, so the distribution stays even.
A reusable function
We can generalize this to any minimum and maximum:
const randomBetween = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min)
}
randomBetween(1, 6) //a dice roll
randomBetween(10, 20) //an integer from 10 to 20, included
The max - min + 1 part counts how many possible values there are. For 10 to 20 that’s 11 values, so we scale the random number to that range and shift it up by min.
If you want the maximum excluded, drop the + 1:
Math.floor(Math.random() * (max - min) + min)
This is handy when picking a random index of an array, where valid indexes go from 0 to length - 1:
const colors = ['red', 'green', 'blue']
colors[Math.floor(Math.random() * colors.length)]
One pitfall
You might be tempted to use Math.round() instead of Math.floor(). Don’t.
With Math.round(), the minimum and maximum values only get half a slice of the range each, while every value in the middle gets a full one. Roll a dice this way and you’ll see 1 and 6 roughly half as often as 2, 3, 4 and 5.
Stick with Math.floor() and the + 1 trick shown above, and every value has the same chance.
One last note: Math.random() is fine for games, sampling, and picking a random item. It’s not cryptographically secure, so don’t use it to generate tokens or passwords.
Related posts about js: