Javascript-Random
The javascript Math.random() function returns a random(floating-point, pseudo-random) number between range [0,1) (0 – inclusive and 1 – exclusive).This random number can then be scaled according to the desired range.
Syntax:
Math.random();
JavaScript Demo: Math.random()
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
console.log(getRandomInt(3));
// expected output: 0, 1 or 2
console.log(getRandomInt(1));
// expected output: 0
console.log(Math.random());
// expected output: a number from 0 to <1
OUTPUT:
1
0
0.4517117295134223
JavaScript Random Integers:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math</h2>
<p> random integer between 0 and 9</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10);
</script>
</body>
</html>
OUTPUT:
JavaScript Math
random integer between 0 and 9
4
Proper Random Function:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p>getRndInteger(min, max) returns a random number between 0
and 9 </p>
<button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">Click Me</button>
<p id="demo"></p>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
</body>
</html>
OUTPUT:
JavaScript Math.random()
getRndInteger(min, max) returns a random number between 0 and 9
4
