How to generate random whole numbers in JavaScript in a specific range?


To generate a random number, use the JavaScript Math.random() method. Here set the minimum and maximum value and generate a random number between them as in the following code −

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <script>
         var max = 6
         var min = 2
         var random = Math.floor(Math.random() * (max - min + 1)) + min;
         document.write(random)
      </script>
   </body>
</html>

Updated on: 15-Jun-2020

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements