To get a random number between a range of numbers using JavaScript, we first need to know how to generate a random number.
To generate a random number using JavaScript, the simplest way is to use the JavaScript random() method:
var random = Math.random();
The Javascript Math random() method generates a number between 0 and 1 (including 0 and excluding 1).
Let’s say we want to generate 10 random numbers between 0 and 1. We can loop 10 times, calling the Math random() method inside the loop, and create an array with these 10 random numbers. Since the numbers returned will be decimals between 0 and 1, to make things more practical, we can multiply the result by 10 and then use the Math.round() method to get an integer value between 0 and 10. We can also multiply by 100 to get a number between 0 and 100, which is what we will do.
var randoms = [];
for (var i = 0; i < 10; i++) {
randoms.push(Math.round((Math.random()*100)))
}
console.log(randoms);
A possible output (because it's random) for generating 10 random numbers using the code above could be:
[78, 58, 16, 1, 34, 27, 81, 79, 62, 22]
Generating a Random Number in a Range Using JavaScript
Generating a random number between 0 and 1 is useful, but many times we need to generate a random number within a range of numbers.
If we want to start the range at a different point other than 0, we need to add or subtract to our random number. To generate a random number in the range between -5 and 5, we first need to multiply our random number by 10 and then subtract 5 as shown below:
var random = Math.rand() * 10 - 5;
Below is a example of using JavaScript to generate a random number in a range of numbers. You can update the inputs and click the button to generate a random number between the two inputs. We will round the number at the end to come up with an integer value.
Code Output:
Our generated random number between 0 and 10 is:
Full Code:
Generate Random Number
Our generated random number between 0 and 10 is:
<script>
function genRandomNum(){
var num1 = Number(document.getElementById("input-num-1").value);
var num2 = Number(document.getElementById("input-num-2").value);
var start, end;
var diff = Math.abs(num2 - num1);
if (num2 > num1) {
start = num1;
end = num2;
} else {
start = num2;
end = num1;
}
document.getElementById("num1").textContent = start;
document.getElementById("num2").textContent = end;
document.getElementById("rand1").textContent = (Math.round(Math.random() * diff + start));
};
</script>
Hopefully this article has been useful for you to understand how to generate a random number in a range of numbers using JavaScript.