Home »
JavaScript
Math.random() Method with Example in JavaScript
JavaScript | Math.random() Method: Here, we are going to learn about the random() method of Math class in JavaScript with Examples.
Submitted by Shivang Yadav, on December 05, 2019
JavaScript | Math.random() Method
Math operations in JavaScript are handled using functions of math library in JavaScript. In this tutorial on Math.random() method, we will learn about the random() method and its working with examples.
Math.random() is a function in math library of JavaScript that is used to support math's operation for finding random numbers between 0 and 1.
Syntax
Math.random();
Parameters
- It does not accept any parameter.
Return Value
The return type of this method is number, it returns a random floating-point number between 0 and 1.
Example 1
console.log(Math.random())
/*0.701135025566191*/
console.log(Math.random())
/*0.6452343021893485*/
console.log(Math.random())
/*0.9068360878808799*/
Example 2: Program to generate a random number within a given range
We have to multiply the generated random number with the range and then add the lower limit of the range to the number.
Example : random number between 10 to 100 is generated using (random_number * (100-10) + 10).
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script>
var min = 10;
var max = 100;
var random = Math.floor(Math.random() * (+max - +min) + +min);
document.write("The generated random number is " + random);
</script>
</body>
</html>
Output
JavaScript Math Object Methods »