JavaScript Math.random() Method
The Math.random() method in JavaScript is used to generate a pseudo-random decimal number between 0 (inclusive) and 1 (exclusive).
Note: The Math.random() is not suitable for cryptographic or security-related purposes. The numbers generated by Math.random() are not truly random and should not be relied upon for tasks that require high security standards. Instead use the Web Crypto API, and more precisely the window.crypto.getRandomValues() method.
Syntax
Following is the syntax of JavaScript Math.random() method −
Math.random()
Parameters
This method does not accept any parameters.
Return value
This method returns a floating-point number, pseudo-random number between 0 (inclusive) and 1 (exclusive).
Example 1
In the following example, the JavaScript Math.random() method generates a random number between 0 to 1 −
<html> <body> <script> const result = Math.random(); document.write(result); </script> </body> </html>
Output
If we execute the above program, it gives a random number between 0 to 1.
Example 2
This example generates a random decimal number between 0 (inclusive) and 10 (exclusive) −
<html> <body> <script> const result = Math.random() * 10; document.write(result); </script> </body> </html>
Output
If we execute the above program, it gives a random number between 0 to 10.
Example 3
The following example generates a random integer between 0 and 99 (inclusive) by multiplying the random decimal by 100 and rounding down using Math.floor() −
<html> <body> <script> const result = Math.floor(Math.random() * 100); document.write(result); </script> </body> </html>
Output
As we can see in the output, it generates random numbers from 0 to 99.