Math.random
Returns a random number between 0 and 1.
Available since: ES1
Syntax
Math.random()Return value
numberA random fraction: at least 0 and strictly less than 1.
Examples
The result differs on every run:
console.log(Math.random());A random integer from 1 to 6:
console.log(Math.floor(Math.random() * 6) + 1);Notes
The method is unsuitable for passwords and confirmation codes: its numbers are predictable. Use crypto.getRandomValues() for those.
See also
- Math.floor — Rounds a number down to an integer.
- crypto.randomUUID — Creates a random unique identifier (UUID).
Related recipes
In the tutorial
- Numbers — Numbers in JavaScript — integers and fractions, rounding, the Math object, toFixed and the special values Infinity and NaN.