JavaScript Math.random()
Examples
let x = Math.random();
Try it Yourself »
Return a random number between 0 and 10:
let x = Math.random() * 10;
Try it Yourself »
Return a random number between 0 and 100:
let x = Math.random() * 100;
Try it Yourself »
A random whole number between 1 and 10:
let x = Math.floor((Math.random() * 10) + 1);
Try it Yourself »
A random whole number between 1 and 100:
let x = Math.floor((Math.random() * 100) + 1);
Try it Yourself »
Definition and Usage
The Math.random()
method returns a random number from 0 (inclusive) up to but not
including 1 (exclusive).
Note
Math.random() does not return a cryptographically secure number.
If you need a cryptographically secure number, use this Crypto API method:
crypto.getRandomValues()
Syntax
Math.random()
Parameters
NONE |
Return Value
Type | Description |
Number | A random number from 0 (inclusive) up to but not including 1 (exclusive). |
Browser Support
Math.random()
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |