Summary
The Math.random()
function returns a floating-point, pseudo-random number in the range [0, 1)
that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
The random number generator is seeded from the current time, as in Java.
Syntax
Math.random()
Parameters
None.
Examples
Example: Using Math.random
Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, these ranges, excluding the one for Math.random()
itself, aren't exact, and depending on the bounds it's possible in extremely rare cases (on the order of 1 in 262) to calculate the usually-excluded upper bound.
// Returns a random number between 0 (inclusive) and 1 (exclusive) function getRandom() { return Math.random(); }
// Returns a random number between min (inclusive) and max (exclusive) function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }
// Returns a random integer between min (included) and max (excluded) // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; }
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition. JavaScript 1.0 (UNIX Only) / JavaScript 1.1 (All platform) | Standard | Initial definition. |
ECMAScript 5.1 (ECMA-262) The definition of 'Math.random' in that specification. |
Standard | |
ECMAScript 6 (ECMA-262) The definition of 'Math.random' in that specification. |
Draft |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Document Tags and Contributors
Contributors to this page: IvanWills, Voracity, bhanubais, nosebleed, Mkmelin, Coopster, evilpie, Marcoos, Brettz9, ytpete, Ted_Mielczarek, WilDoane, Sheppy, yurtsevich, fscholz, Nickolay, jvendryes, Waldo, paulofreitas, ethertank, Mgjbot, Maian, Dria
Last updated by:
ytpete,