You can simply use the Math.random() method in combination with the Math.floor() method to generate a random number between two numbers in JavaScript.
The Math.random() method returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1), whereas the Math.floor() method round the number down to the nearest integer. Let's take a look at the following example to see how it works:
/* Defining a custom function which returns a random number
between min and max, including min and max */
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// Generate a random number between 1 and 10 (including 1 and 10)
var randomNum = generateRandomNumber(1, 10);
console.log(randomNum);
Use the
Math.random()MethodYou can simply use the
Math.random()method in combination with theMath.floor()method to generate a random number between two numbers in JavaScript.The
need an explanation for this answer? contact us directly to get an explanation for this answerMath.random()method returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1), whereas theMath.floor()method round the number down to the nearest integer. Let's take a look at the following example to see how it works: