javascript random number

JavaScript Random Number

For JavaScript random number, we used the Math.random( ) function. This method returns the value between 0 (inclusive) and 1 (exclusive).

Syntax :

Math.random();

Example :

<html>
<head>
<title>Developer Helps | Javascript Random Number</title>
</head>
<body>
<h2>Javascript Random Number</h2>

Random Number between 0 and 1: <p id="random-number"></p>

<script>
document.getElementById("random-number").innerHTML = Math.random();
</script>

</body>
</html>

Output :

Javascript Random Number

Random Number between 0 and 1:
0.2535062639322767

JavaScript Random Integers

This example returns the random integer from 0 to 9.

Example :

<html>
<head>
<title>Developer Helps | Javascript Random Number</title>
</head>
<body>
<h2>Javascript Random Number</h2>

Random Integer between 0 and 9: <p id="random-number"></p>

<script>
document.getElementById("random-number").innerHTML = Math.floor(Math.random() * 10);
</script>

</body>
</html>

Output :

Javascript Random Number

Random Integer between 0 and 9:
2

JS Random Function

This JavaScript function returns a random number between min (included) and max (excluded).

Function :

function fetchRandomInteger(min, max) 
{
  return Math.floor(Math.random() * (max - min)) + min;
}

Example :

<html>
<head>
<title>Developer Helps | Javascript Random Number</title>
</head>
<body>
<h2>Javascript Random Number</h2>
<button onclick="fetchRandomInteger(0,10)">Try Click</button><br><br>
Random Function between min and max: <p id="random-number"></p>

<script>
function fetchRandomInteger(min, max) 
{
  document.getElementById("random-number").innerHTML = Math.floor(Math.random() * (max - min)) + min;
}
</script>

</body>
</html>

Output :

Javascript Random Number

Try Click

Random Function between min and max:
8

Thanks for the reading post. I hope you like and understand the post. If you have any doubt regarding this post please comment below.

More Related Post

Leave a comment

Your email address will not be published. Required fields are marked *

0 0 0
FOLLOW ON