JavaScript Reference ยท Math
Math.random()
Reference for Math.random(): generating random numbers, integers in a range, shuffling and picking items, plus why it is not suitable for security.
Math.random() returns a pseudo-random floating-point number that is at least 0 and less than 1. It takes no arguments. Every other kind of random value, such as a dice roll, a random array item or a shuffled deck, is built by scaling and rounding this one number.
The numbers come from an algorithm that the browser or runtime seeds for you. You cannot choose the seed, so you cannot reproduce a sequence, and the output is not safe for passwords, tokens or anything an attacker might want to guess.
Math.random()
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Math.random()
Parameters: none.
Return value: a number n where 0 <= n < 1. Zero can be returned; one never is.
Exceptions: none.
Usage notes
- The range is half-open.
Math.floor(Math.random() * 10)yields0to9, never10. To include the upper bound, add one before flooring, asrandomInt()above does. - Do not use it for security. For tokens, passwords, session IDs or shuffling in a game with money at stake, use
crypto.getRandomValues()orcrypto.randomUUID(). - No seed. You cannot replay a sequence. For reproducible tests or procedural generation, write or import a seeded generator like the one in the second example.
- Sorting is not shuffling.
array.sort(() => Math.random() - 0.5)gives a biased result and depends on the sort algorithm. Use the Fisher-Yates loop shown above. - Rounding with
Math.round()gives the two end values of a range only half the probability of the others. UseMath.floor(). - Distribution. Output is approximately uniform, which suits games and simulations but not rigorous statistics.
- Precision. Results have about 52 bits of randomness, so they can be multiplied by large ranges, but not beyond
Number.MAX_SAFE_INTEGER.
Browser support
Supported in every browser and in Node.js. The quality of the generator differs between engines, which is another reason not to rely on it for security.