Javascript Math Random: How to Use Math.random()
Javascript Math.random() is an inbuilt method that returns a random number between 0 (inclusive) and 1 (exclusive). The implementation selects the initial seed to a random number generation algorithm; it cannot be chosen or reset by the user.
Javascript Math Random Example
The Math.random() method returns a random number between 0 (inclusive) and 1 (exclusive).
Syntax
The syntax of Math.random() function is following.
Math.random()
Return Value
It returns the floating-point, a pseudo-random number between 0 (inclusive) and 1 (exclusive).
Let’s see the example.
// app.js console.log(Math.random());
Output
The Math.random() does not provide the cryptographically secure random numbers. Do not use them for anything related to security.
Getting a random number between two values
The Math.random() method explicitly does not provide the arguments that can return the values between two numbers. Although we can create a method that can do for you. See the following example.
// app.js const app = (min, max) => { return Math.random() * (max - min) + min; } console.log(app(19, 25));
Output
All the random values will be generated between those two arguments. In the above example, all the values are generated in floating values. You can also generate the integer values as well. See the following example.
// app.js const app = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(app(19, 25));
Output
So, we have seen how we can use the Math.random() function to generate the random values in float as well as an integer.
Finally, Javascript Math Random Example is over.