We can use JavaScript to get a random number between 1 and 100. 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:

`[42, 54, 25, 68, 57, 4, 43, 24, 19, 92]`

## Using JavaScript to Get a Random Number Between 1 and 100

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 100:

```
<div id="div">
<div id="click-me" onclick="genRandomNum()">Generate Random Number between 1 and 100</div>
<p>Our generated random number between 1 and 100 is: <span id="rand1"></span></p>
</div>
```

And here is our JavaScript code to generate a random number between 1 and 100:

```
function genRandomNum(){
var diff = Math.abs(100 - 1);
document.getElementById("rand1").textContent = (Math.round(Math.random() * diff + 1));
};
```

And here is the example of generating a random number between 1 and 100.

Code Output:

Our generated random number between 1 and 100 is:

Full Code:

```
<div id="div">
<div id="click-me" onclick="genRandomNum()">Generate Random Number between 1 and 100</div>
<p>Our generated random number between 1 and 100 is: <span id="rand1"></span></p>
</div>
<script>
function genRandomNum(){
var diff = Math.abs(100 - 1);
document.getElementById("rand1").textContent = (Math.round(Math.random() * diff + 1));
};
</script>
```

Hopefully this article has been useful for you to understand how to use JavaScript to get a random number between 1 and 100.

## Leave a Reply