The JavaScript Math random() method is used to generate a random number between 0 (inclusive) and 1 (exclusive).
This method is commonly used in games to generate random moves or outcomes, in security for creating tokens or random IDs, and for many other purposes.
Syntax
Math.random()
Parameters
It does not accept any argument.
Return Value
Returns the floating point, a pseudo-random number between 0 (inclusive) and 1 (exclusive).
Visual Representation Example 1: How to Use Math random() Method
console.log(Math.random());
Output
0.9021557865102012
Example 2: Generating a Random Number Between Two Values
const getNumber = (min, max) => {
return Math.random() * (max - min) + min;
}
console.log(getNumber(10, 50));
Output
37.815078037214356
Example 3: Generating a Random Integer within a Specified Range
const getNumber = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getNumber(10, 50));
Output
16
Browser compatibility
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Opera 3 and above
- Safari 1 and above