Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
Math.random()

Try it

JS Random numbers in a range

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Picking and shuffling (seeded demo)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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) yields 0 to 9, never 10. To include the upper bound, add one before flooring, as randomInt() 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() or crypto.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. Use Math.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.