JavaScript Random

JavaScript Random numbers are created with Math.random() function. It is mentioned below:

Random Function

Creating a proper random function to use for all random integer purposes can be a good idea. The following JavaScript function always returns a random number between min (included) and max (excluded):

<!DOCTYPE html>
<html>
<body>

<button onclick="document.getElementById('tacode').innerHTML = getRndInteger(0,8)">Click Me</button>

<p id="tacode"></p>

<script>
function getRndInteger(n, x) {
  return Math.floor(Math.random() * (x - n) ) + n;
}
</script>

</body>
</html>

Output:

JavaScript Random

The following JavaScript function always returns a random number between min and max (both included):

<!DOCTYPE html>
<html>
<body>

<button onclick="document.getElementById('tacode').innerHTML = getRndInteger(1,8)">Click Me</button>

<p id="tacode"></p>

<script>
function getRndInteger(n, x) {
  return Math.floor(Math.random() * (x - n + 1) ) + n;
}
</script>

</body>
</html>

Output:

image 98

Math.random()

The Math.random() method is used to return a random number between 0 (inclusive),  and 1 (exclusive). It always returns a number less than 1.

JavaScript Random – Integers

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