Generating Random Numbers in JavaScript - by Javascript Jeep?? - Better Programming - Medium
Generating Random Numbers in JavaScript - by Javascript Jeep?? - Better Programming - Medium
Image by NeONBRAND
Here, the random number doesn’t mean that you always get a unique number. It
generates the same number only after some interval. The interval here is very long,
so you probably won’t get the same number twice.
https://medium.com/better-programming/generating-random-numbers-in-javascript-4b2a1e9d1806 1/4
25/08/2020
rand(10); // 5.500949568251157
Math.ceil() → to round up
// using Math.floor
return Math.floor(rand);
To get a random number between two numbers ( min included, max excluded):
return Math.floor(randomNum);
https://medium.com/better-programming/generating-random-numbers-in-javascript-4b2a1e9d1806 2/4
25/08/2020
rand(10, 20);
In the above code, (max-min) + min is just to handle if there is any case when the
max is less than the min. In such a case, where max is less than min:
max = 5, min = 10
return Math.round(randomNum);
rand(10, 20);
https://medium.com/better-programming/generating-random-numbers-in-javascript-4b2a1e9d1806 3/4
25/08/2020
https://medium.com/better-programming/generating-random-numbers-in-javascript-4b2a1e9d1806 4/4