Categories
JavaScript Web development

JavaScript random() Method

JavaScript random() Method

The JavaScript random() method returns a random number from 0 (included) up to but not including 1.

Syntax:

Math.random()

Example:

<!DOCTYPE html>
<html>
<body>

<p id="example"></p>

<script>
document.getElementById("example").innerHTML = Math.random();
</script>

</body>
</html>

Output:


Math.random() used with Math.floor() can be used to return random integers:

<!DOCTYPE html>
<html>
<body>

<p>Every time you click the button, getRandomInteger(min, max) returns a random number between 1 and 20 (both included):</p>

<button onclick="document.getElementById('example-2').innerHTML = getRandomInteger(1,20)">Click Me</button>

<p id="example-2"></p>

<script>
function getRandomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}
</script>

</body>
</html>

Output:

Every time you click the button, getRandomInteger(min, max) returns a random number between 1 and 20 (both included):



Enjoy coding!