To generate a random number in JavaScript, use the Math.random() function. JavaScript provides a Math module that supports all type of mathematical functions that helps us carry out complex math calculation.
JavaScript Math.random
The Math.random() is a built-in JavaScript method that returns a random number between 0 (inclusive) and 1 (exclusive). The Math.random() function does not accept any argument and returns the value between 0 to 1, in which 1 is exclusive, and 0 is inclusive.
Syntax
Math.random()
Parameters
It does not accept any argument.
Return Value
The Math.random() function returns the floating point, a pseudo-random number between 0 (inclusive) and 1 (exclusive).
Example
// app.js console.log(Math.random());
Output
The Math.random() does not provide cryptographically secure random numbers. Therefore, 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. However, we can create a method that can do this for you.
// 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 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 a float and an integer.
That’s it.