The Math.random()
method generates a random float (a number with decimals) between 0
and 1
. What if you wanted a random integer, or whole number, instead of a float?
In this snippet, look at how to get a random integer between two numbers. For example, let’s say you wanted a number that was at least 5, but no bigger than 42.
var randomNumber = function (min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
};
// Logs something like 37
var rand = randomNumber(5, 42);
console.log(rand);
Source
https://gomakethings.com/generating-random-numbers-with-vanilla-js/