Skip to content

JavaScript random number between 1 and 10 | Example code

Use Math.random() used with Math.floor() to return get integers (number) between 1 and 10 in JavaScript.

Math.floor(Math.random() * 10) + 1;

JavaScript random number between 1 and 10 Example code

Complete HTML example code.

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        var random = Math.floor(Math.random() * 10) + 1;  
        alert(random);
    </script>
</body>
</html>

Output:

JavaScript random number between 1 and 10

Create a Function to Generate random number

This JavaScript function will returns a random number between min (included) and max (excluded):

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        function getRndNum(min, max) {
          return Math.floor(Math.random() * (max - min) ) + min;
      }

      console.log(getRndNum(1,9));
  </script>
</body>
</html>

Output: 6

Do comment if you have any doubts and suggestion on this example.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “JavaScript random number between 1 and 10 | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading