Basically ‘Math.random()’ function will generate a random decimal floating number range from 0.0 to 1.0 and thus we need to multiple the generate number by 10 and round it to the nearst integer number by using Math.floor() function.
Here is a example
var rand = Math.random(); console.log(rand); //0.7520321036592579 let random_number = Math.floor(rand * 10) + 1; console.log(random_number); // 8
In above code, Math.random() function will generate random number from 0.0 to 1.0 [ 0.7520… is the generated number], then to make it range between 1 – 10 I am multiply it with 10 and add 1 to it because math.floor will round to 1 – 9.
Now say you want to generate a number between 1 to 100, so can we acheived by just modifying the scaling and shift value i.e just be multiplying the random number generated by 100 and adding 1 to it . For example:
let randomNumber = Math.floor(Math.random() * 100) + 1; console.log(randomNumber);