We can use JavaScript to get a random number between 1 and 5. To do this 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:
[40, 9, 77, 66, 62, 55, 40, 89, 57, 30]
Using JavaScript to Get a Random Number Between 1 and 5
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.
You can check out this post to learn how to do this.
Here will be our HTML setup to generate a random number in the range between 1 and 5:
Generate Random Number between 1 and 5
Our generated random number between 1 and 5 is:
And here is our JavaScript code to generate a random number between 1 and 5:
function genRandomNum(){
var diff = Math.abs(5 - 1);
document.getElementById("rand1").textContent = (Math.round(Math.random() * diff + 1));
};
And here is the example of generating a random number between 1 and 5.
Code Output:
Our generated random number between 1 and 5 is:
Full Code:
Generate Random Number between 1 and 5
Our generated random number between 1 and 5 is:
Hopefully this article has been useful for you to understand how to use JavaScript to get a random number between 1 and 5.