The Javascript Math.random() method is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive), and 1 (exclusive). This random number can be scaled according to the desired range.
Syntax:
Math.random()
Return Value: The Math.random() method returns a value less than 1.
Example: This example uses Math.random() function to return a random number.
html
<h2>Math.random()</h2>
<p>
Math.random() returns a random
number between 0 and 1
</p>
<p id="GFG"></p>
<script>
document.getElementById("GFG").innerHTML
= Math.random();
</script>
|
Output:
Random Integers: The Math.random() method is used with Math.floor() function to return random integers.
Example: This example generated a random number every time we run the code.
html
<center>
<p>
Math.floor(Math.random() * 11) returns
a random integer between 0 and 10
(inclusive):
</p>
<p id="demo"></p>
</center>
<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 11);
</script>
|
Output:
Note: The output of the code varies every time we run the code.
Proper Random Function: The javaScript function always returns a random number between min and max where min is inclusive and max may be inclusive or exclusive.
Example: This example generates a proper random number.
html
<p>
When you click the button it will
give a random value between 0 and
9 both inclusive:
</p>
<button onclick="document.getElementById('GFG').innerHTML =
getRndInteger(0, 10)">Try it</button>
<p id="GFG"></p>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
|
Output:
We have a complete list of Javascript Math Objects methods, to check those please go through this Javascript Math Object Complete reference article.
Supported Browsers:
- Google Chrome 1 and above
- Edge 12 and above
- Internet Explorer 3 and above
- Firefox 1 and above
- Opera 3 and above
- Safari 1 and above
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
03 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...