The built in Math.random()
method generates a random number between 0 and 0.9999999.
Typically this floating point number is not what you want. Here are a couple of ways to generate whole numbers:
MDN method
Using the random number from the MDN beginner guide which generates a number between 1 and 100.
let randomNumber = Math.floor(Math.random() * 100) + 1;
So Math.random()
generates a number between 0 and less than 1.
Multiplying by 100 means you get a number between 0 and 99.
The Math.floor()
function rounds the result DOWN to the nearest whole number.
Adding 1 means the numbers are now between 1 and 100.
Josh Comeau function
Another function is this one by Josh Comeau.
const randomNo = (min, max) => Math.floor(Math.random() * (max - min)) + min;
This takes two arguments, the lowest and highest numbers. So for say a straight percentage you’d pass 0
and 101
.
Why 101
? Josh says:
This random function includes the lower bound, but excludes the upper bound. For example,
randomNo(10, 12)
will grant either10
or11
, but never12
.This was done intentionally, to match the behaviour of Math.random, as well as JavaScript methods like slice.