var = randNum;
function getRandomNum(min, max){ return Math.floor(Math.random() * (max- min + 1)+ min)
randNum = getRandomNum(1 , 6);
console.log(randNum);
var = randNum;
function getRandomNum(min, max){ return Math.floor(Math.random() * (max- min + 1)+ min)
randNum = getRandomNum(1 , 6);
console.log(randNum);
Let's breakit down
We need to find random number in range (min, max)
Math.random()
returns a random number between 0 and 1(excluded)
Ex (0.1, 0. 245, ... so on)
Since our range starts from min
Hence we need to add min to the random number min + Math.random()
But this will allow you random values only from min
to min + 1
To make sure that we cover the entire range from min to max, we multiply the difference between those numbers max - min
This is good, but we only need Integer
numbers, hence we round it to floor value using Math.floor
And to account for that exclude 1
from Math.random()
we add it to the value
Hence it becomes Math.floor(Math.random() * (max- min + 1)+ min)