JavaScript Random - JavaScript Math random() Method



Math.random()

  • Math.random() returns a random number between 0 (inclusive), and 1 (exclusive).
js-math-random

Sample Code

<!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>Document</title>
    </head>
<body>
   
    Random Number is: <span id="p2"></span>    <br>
   
    <script>    
    
    document.getElementById('p2').innerHTML=Math.random();    
     
    </script>    
</body>
</html>

Output

Random Number is: 0.9105302265364117

JavaScript Random Integers

  • Math.random() used with Math.floor() can be used to return random integers.

Sample Code

<script>
        document.getElementById("p2").innerHTML =
    Math.floor(Math.random() * 30);
</script> 

Output

25

Related Searches to JavaScript Random - JavaScript Math random() Method