Random Number Generation in JS: How It Works

How-to basics · Updated November 23, 2026

In JavaScript, random number generation is done with the built-in Math.random() function, which returns a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). To get an integer in a specific range, you multiply and round the result, for example Math.floor(Math.random() * (max - min + 1)) + min.

What Math.random() Actually Returns

Math.random() returns a number in the half-open interval [0, 1). That means it can return exactly 0, but it will never return exactly 1. The value is a 64-bit floating-point approximation of a real number, so it has about 15–17 significant decimal digits. For most everyday uses—like picking a random array element, shuffling a list, or generating a random color—this is enough.

Here is a simple example:

const randomFraction = Math.random(); // e.g., 0.734528190234567
console.log(randomFraction);

Because the result is always less than 1, multiplying it by a range and flooring gives you a uniform integer distribution across that range, assuming the underlying generator is uniform.

How to Generate a Random Integer in a Range

The most common need is a random integer between a minimum and maximum (inclusive). The standard formula is:

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

This works because Math.random() gives a value from 0 up to but not including 1. Multiplying by (max - min + 1) gives a range from 0 up to (but not including) that count. Adding min shifts it to the desired start. For example, getRandomInt(1, 6) simulates a die roll, returning 1, 2, 3, 4, 5, or 6 with equal probability.

If you need a random element from an array, you can do:

const items = ['apple', 'banana', 'cherry'];
const randomItem = items[Math.floor(Math.random() * items.length)];

This picks an index from 0 to length - 1.

Why It’s Called “Pseudo-Random”

JavaScript’s Math.random() is not truly random; it is generated by a deterministic algorithm called a pseudo-random number generator (PRNG). The algorithm starts from a seed value and produces a sequence of numbers that appear random but are completely determined by that seed. For most applications, this is fine because the seed is set automatically from system entropy (like mouse movements or system time) at page load.

However, because it’s deterministic, if you knew the seed and the algorithm, you could predict the entire sequence. This makes Math.random() unsuitable for cryptography, security tokens, or anything where unpredictability is a security requirement. For those cases, you need a cryptographically secure generator.

Cryptographically Secure Random Numbers

For security-sensitive applications, use the Web Crypto API. The crypto.getRandomValues() method fills a typed array with cryptographically secure random values. It is available in all modern browsers and in Node.js (via the crypto module).

Example to get a secure random integer between 0 and 255:

const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
const randomInt = array[0] % 256; // not perfectly uniform but fine for many uses

A better uniform approach for a range is to use rejection sampling:

function secureRandomInt(max) {
  const range = max + 1;
  const maxUint = 0xFFFFFFFF;
  const limit = maxUint - (maxUint % range);
  const buf = new Uint32Array(1);
  let x;
  do {
    window.crypto.getRandomValues(buf);
    x = buf[0];
  } while (x >= limit);
  return x % range;
}

In Node.js, you can use crypto.randomBytes() or crypto.randomInt() for secure integers.

Common Pitfalls and Misconceptions

One common mistake is using Math.round() instead of Math.floor() when generating integers. Math.round() creates a non-uniform distribution because the edges (min and max) have half the probability of the middle values. Always use Math.floor().

Another pitfall is ignoring the fact that Math.random() can return 0 but never 1. If you use Math.ceil() on a multiplication, you can get a result that is sometimes 0 when you expect 1. The correct pattern is always Math.floor() plus an offset.

There is also a misconception that you can seed Math.random() to reproduce sequences. In standard JavaScript, there is no built-in way to set the seed. Some environments (like V8) may allow it through flags, but that’s not portable. If you need reproducible random sequences (for games or simulations), you must implement your own PRNG, such as a linear congruential generator or a mulberry32 algorithm.

How to Choose the Right Method

Choosing between Math.random() and crypto.getRandomValues() depends on your use case:

  • Non-security uses (games, UI randomization, shuffling non-sensitive data): Math.random() is fast and sufficient.
  • Security uses (password generation, tokens, encryption keys, lottery draws): use crypto.getRandomValues() or Node’s crypto.randomInt().
  • Reproducible sequences (testing, procedural generation): implement a seeded PRNG like mulberry32.

Always consider performance: Math.random() is extremely fast, while crypto.getRandomValues() is slower because it pulls from system entropy. For bulk random numbers (e.g., millions), stick with Math.random() unless security is required.

Alternatives and Libraries

Several libraries provide more advanced random number generation:

  • seedrandom: a small library that lets you create seeded PRNGs with a consistent API.
  • chance.js: provides a wide range of random generators for names, addresses, etc.
  • faker.js: generates fake data, often used for testing.

For Node.js, the built-in crypto module offers randomInt() which is both secure and convenient:

const { randomInt } = require('crypto');
randomInt(1, 7, (err, n) => { console.log(n); }); // die roll

If you need a normal distribution (bell curve) instead of uniform, you can use the Box-Muller transform on Math.random() values.

Frequently Asked Questions

Can I set the seed for Math.random()?

No, the ECMAScript specification does not provide a way to seed Math.random(). Some engines may have non-standard extensions, but they are not reliable across browsers. For reproducible randomness, implement your own PRNG or use a library like seedrandom.

Is Math.random() safe for passwords?

No. Math.random() is not cryptographically secure; its output can be predicted if the seed is known. For passwords or tokens, always use crypto.getRandomValues() or a dedicated secure random source.

Why does Math.random() sometimes return 0?

Because the interval is [0, 1), the value 0 is possible, though extremely unlikely (about 1 in 2^53). It’s a valid outcome. If you need a number strictly greater than 0, you can add a tiny epsilon or use Math.random() || 1e-10.

How do I generate a random float in a specific range?

Multiply Math.random() by the range width and add the minimum: Math.random() * (max - min) + min. This gives a float between min (inclusive) and max (exclusive). For inclusive max, you can use Math.random() * (max - min) + min and then handle edge cases.

What is the difference between Math.random() and crypto.getRandomValues()?

Math.random() is fast, pseudo-random, and not secure. crypto.getRandomValues() is slower but cryptographically secure, drawing from system entropy. Use the latter for anything security-related.

Can I use Math.random() for shuffling a deck of cards?

Yes, for a game where security isn’t a concern, Math.random() is fine. However, if the shuffle must be unpredictable (e.g., online poker for money), use a secure random source to prevent prediction attacks.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.