JavaScript Math.random()

JavaScript Math.random() method returns a floating point number that is randomly picked from 0 until 1.

Syntax

The syntax of random() method is

</>
Copy
Math.random()

Examples

In the following example, we call Math.random() method to get a random number in the range [0, 1).

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var x = Math.random();
        document.getElementById('output').innerHTML = x;
    </script>
</body>
</html>

In the following example, we call Math.random() method to get a random number in the range [min, max) using the formula.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var min = 2, max = 8;
        var x = min + (max-min)*Math.random();
        document.getElementById('output').innerHTML = x;
    </script>
</body>
</html>

If we want random integer number, then we may use Math.floor() method for the result in the above example.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var min = 2, max = 8;
        var x = Math.floor(min + (max-min)*Math.random());
        document.getElementById('output').innerHTML = x;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we have learnt about Math.random() function, with examples.