To generate a random number using JavaScript, the simplest way is to use the JavaScript random() method:

var random = Math.random();

Random number generation with JavaScript is easy to do. All we need is the Javascript Math random() method.

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:

[100, 50, 11, 2, 32, 53, 84, 71, 65, 24]

Generating a Random Number on Click Using JavaScript

To generate a random number on click using JavaScript, we can combine the Math random() method with a click event.

Let's say we have the following HTML, and we want to give the user the ability to generate a random number and show the random number in a span.

Generate random number

Our generated random number is:

We can utilize the onclick event, Math random() method, the Math round() method, and the innerHTML property to change the text of the span.

Below is the JavaScript code which will allow the user to be able to update the text in the paragraph with a random number. We will do as we did above and multiply the number by 100 and round it to get and integer from 0 to 100.

function genRandomNum(){
  document.getElementById("rand").innerHTML = (Math.round((Math.random()*100)));
}

The final code and output for this example of how to generate a random number on click using Javascript is below:

Code Output:

Generate random number

Our generated random number is:

Full Code:


Generate random number

Our generated random number is:

<script> function genRandomNum(){ document.getElementById("rand").innerHTML = (Math.round((Math.random()*100))); } </script>

Hopefully this article has been useful for you to understand how to generate a random number using Javascript.

Categorized in:

JavaScript,

Last Update: February 26, 2024