In JavaScript, the Math.random
function will generate a random floating point number between 0 and 1(0 is included 1 is excluded):
Math.random();
Let’s say we need to generate a random number under 100. To do this, we would multiply the random number by 100. Math.random()
will not return 1, so the value will be below 100.
Math.random() * 100; // 84.06448370345245
We can use Math.floor
to round it down as shown here:
function generateRandom(maxLimit = 100){let rand = Math.random() * maxLimit;console.log(rand); // say 99.81321410836433rand = Math.floor(rand); // 99return rand;}generateRandom(); // 43generateRandom(500); // 165
In this case, we will have a MIN
and a MAX
value and will need to include the MIN
value and exclude the MAX
value.
If the MIN
value is always 0
, then we can multiply the random number with the MAX
value, but if the MIN
value is other than 0
, we need to find the difference
between MAX
and MIN
. Then we will multiply the random number with that difference
and add the MIN
value.
MIN = 3
& MAX = 5
.MAX - MIN = 2
.MIN(3)
value to the random number, the result is either 3
or 4
. We can see this as follows:function generateRandom(min = 0, max = 100) {// find difflet difference = max - min;// generate random numberlet rand = Math.random();// multiply with differencerand = Math.floor( rand * difference);// add with min valuerand = rand + min;return rand;}console.log(generateRandom());
The above can be also be written as:
const random = (min, max) => Math.floor(Math.random() * (max - min)) + min;