Skip to content

JavaScript random integer between 0 and ‘x’ | Example code

  • by

Use the basic Math methods to get a random integer in JavaScript. The math random() method returns a random number between 0 and 1 (including 0, excluding 1).

You can Multiply this number by the highest desired number (e.g. 10) and Round it downward to its nearest integer.

Example of JavaScript random integer

Example of returns a random integer from 0 to 9 in JS.

 <!DOCTYPE html> 
    <html> 
    <body> 
            <script language="JavaScript">
                var random_int = Math.floor(Math.random() * 10); 
                
                alert(random_int);
            </script>     
    </body> 
    </html> 

Output: Your output could be different and between 0 to 9.

Example of JavaScript random integer

Random integer Function in JS

You can create a function for it:-

function getInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}

Do comment if you know any other way to do it or have any questions.

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

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *