How to generate a random number in JavaScript?

Generating a random  number

To generate a random number, Math.random() is used. We can even generate a number between specified numbers such as between 1 and 10, between 0 and 100, etc. Let's discuss it using an example.




In the following example, using Math.random() function inside a Math.floor() function, which results in integer values, a random number is found out between the numbers 1 and 100. Since we have used an expression (Hl - Ll + 1), where Hl is the higher limit and Ll is the lower limit, inside the Math.floor() function, a random value can even include 1 and 100. if we want to exclude the extremes, remove 1 from the above-mentioned expression so that the expression looks like (Hl - Ll).

<p>Generating a random integer</p>
   <input type = "button" onclick="document.getElementById('random').innerHTML = randIntr(1,100)"
   value = "generate">
<p id="random"></p>
   function randIntr(Hl, Ll) {
      return Math.floor(Math.random() * (Hl - Ll + 1) ) + Ll;

Once the function is executed, the following will be displayed on the screen.

Once we click on the button generate we will get a random number as shown in the output. 


Published on 23-Aug-2019 18:00:35