The JavaScript Math.random() method returns the random number between 0 (inclusive) and 1 (exclusive).
In this article you will learn about “How to generate random number in JavaScript?”.
Syntax
Math.random()
Parameters
Math.random() method does not require any parameters.
Return Value
The Math.random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).
Example
Below is an example to find out the random number between 0 and 1.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example to find out random number between 0 and 1</title>
</head>
<body>
<script>
document.writeln(Math.random())
</script>
</body>
</html>
Example 2
Below is a JavaScript function which always returns a random number between min and max (both included).
<!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>
More examples
// Returns a random number:
Math.random();
// Returns a random integer from 0 to 9:
Math.floor(Math.random() * 10);
// Returns a random integer from 0 to 10:
Math.floor(Math.random() * 11);
// Returns a random integer from 0 to 99:
Math.floor(Math.random() * 100);
// Returns a random integer from 0 to 100:
Math.floor(Math.random() * 101);
// Returns a random integer from 1 to 10:
Math.floor(Math.random() * 10) + 1;
// Returns a random integer from 1 to 100:
Math.floor(Math.random() * 100) + 1;
//This JavaScript function always returns a random number between min (included) and max (excluded):
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}