JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
JavaScript Random
Math.random()
Math.random() is used to return a random number between 0 (inclusive), and 1 (exclusive):
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p>Math.random() returns a random number between 0 (included) and 1 (excluded):</p>
<p id=”demo”></p>
<script>
document.getElementById(“demo”).innerHTML = Math.random();
</script>
</body>
</html>
Output
JavaScript Math.random()
Math.random() returns a random number between 0 (included) and 1 (excluded):
JavaScript Random Integers
Math.random() used with Math.floor() returns random integers.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math</h2>
<p>Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both
included):</p>
<p id=”demo”></p>
<script>
document.getElementById(“demo”).innerHTML =
Math.floor(Math.random() * 10);
</script>
</body>
</html>
Output
JavaScript Math
Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both included):
Another Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math</h2>
<p>Math.floor(Math.random() * 100)) returns a random integer between 0 and 99
(both included):</p>
<p id=”demo”></p>
<script>
document.getElementById(“demo”).innerHTML =
Math.floor(Math.random() * 100);
</script>
</body>
</html>
Output
JavaScript Math
Math.floor(Math.random() * 100)) returns a random integer between 0 and 99 (both included):
This JavaScript function returns a random number between min and max (both included):
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p>Every time you click the button, getRndInteger(min, max) returns a random number between 1 and 10 (both included):</p>
<button onclick=”document.getElementById(‘demo’).innerHTML = getRndInteger(1,10)”>Click Me</button>
<p id=”demo”></p>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max – min + 1) ) + min;
}
</script>
</body>
</html>
Output
JavaScript Math.random()
Every time you click the button, getRndInteger(min, max) returns a random number between 1 and 10 (both included):