JavaScript Random Number: How to Generate One

How-to basics · Updated November 23, 2026

To generate a random number in JavaScript, use Math.random(), which returns a floating-point number between 0 (inclusive) and 1 (exclusive). For a random integer in a specific range, combine it with Math.floor(), like Math.floor(Math.random() * (max - min + 1)) + min.

How Math.random() Works

Math.random() is a built-in method of the Math object. It uses a pseudo-random number generator (PRNG) that produces a deterministic sequence of numbers that appears random. The algorithm is implementation-dependent—most modern browsers use a variant of the xorshift or Mersenne Twister. The returned value is a decimal from 0 up to but not including 1, meaning it can be 0 but never 1. This is a key detail because it affects how you scale the result to your desired range.

For example, Math.random() might return 0.2345678901234567. To get a number between 0 and 10, multiply by 10: Math.random() * 10 gives a value from 0 to 9.999…, and Math.floor(Math.random() * 10) gives an integer from 0 to 9.

Generating Random Integers in a Range

The most common task is generating a random integer between a minimum and maximum value, inclusive. The formula is:

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

Here’s why it works: (max - min + 1) gives the number of possible integers. Multiplying Math.random() by that gives a value from 0 up to (but not including) the count. Adding min shifts the range. For example, getRandomInt(5, 10) yields one of 6, 7, 8, 9, or 10, each with equal probability. The Math.ceil() and Math.floor() calls ensure that if you pass non-integer bounds, they are rounded correctly to avoid off-by-one errors.

If you need a random integer from 0 to a maximum (exclusive), a simpler form is Math.floor(Math.random() * max). For instance, Math.floor(Math.random() * 6) simulates a die roll (1–6 would require adding 1).

Random Floating-Point Numbers

Sometimes you need a random decimal, not an integer. To get a random float between two values, use:

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

This returns a value from min (inclusive) to max (exclusive). For example, getRandomFloat(1.5, 3.5) could return 1.5, 2.789, or 3.4999, but never 3.5. If you need to include the upper bound, you can adjust the formula, but that is rarely necessary in practice.

Common Pitfalls and Misconceptions

A frequent mistake is writing Math.floor(Math.random() * max) + min without the +1, which excludes the maximum value. Another is using Math.round() instead of Math.floor(); Math.round() creates a biased distribution because the endpoints have half the probability of the middle values. For example, Math.round(Math.random() * 3) gives 0, 1, 2, or 3, but 1 and 2 are twice as likely as 0 and 3.

Also, Math.random() is not cryptographically secure. It is fine for games, shuffles, or random UI selection, but never use it for passwords, tokens, or security-sensitive features. For those, use the Web Crypto API’s crypto.getRandomValues().

Cryptographically Secure Random Numbers

For security-critical applications, use crypto.getRandomValues() to generate random integers. It returns a typed array filled with cryptographically strong random values. To get a random integer in a range:

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

This method avoids modulo bias, which occurs when the range does not evenly divide the total number of possible values. The loop rejects values that would cause bias. This is the approach recommended for generating lottery numbers, session IDs, or any random value that must be unpredictable.

Practical Examples and Use Cases

Random numbers are used in many everyday JavaScript tasks:

  • Dice roll: Math.floor(Math.random() * 6) + 1 gives 1–6.
  • Random array element: arr[Math.floor(Math.random() * arr.length)] picks a random item.
  • Shuffling an array: Use the Fisher–Yates shuffle, which relies on random indices.
  • Random color: Generate a hex color like '#' + Math.floor(Math.random()*16777215).toString(16).
  • Simple game AI: Choose a random action from a set.

For a random password, combine crypto.getRandomValues() with a character set and modulo to avoid bias.

Performance and Alternatives

Math.random() is extremely fast, typically taking less than a microsecond per call. It is suitable for most applications, even those generating millions of numbers. If you need a reproducible sequence (for testing or procedural generation), you can implement a seeded PRNG, such as a simple linear congruential generator (LCG). For example:

function seededRandom(seed) {
  let s = seed % 2147483647;
  if (s <= 0) s += 2147483646;
  return function() {
    s = (s * 16807) % 2147483647;
    return (s - 1) / 2147483646;
  };
}
const rand = seededRandom(42);
console.log(rand()); // always the same sequence for seed 42

This is useful when you need the same sequence of random numbers across runs, such as in a game level generator or a simulation.

Frequently Asked Questions

How do I generate a random number between 1 and 10 in JavaScript?

Use Math.floor(Math.random() * 10) + 1. This gives an integer from 1 to 10 inclusive. The * 10 scales to 0–9, and +1 shifts to 1–10.

Why is Math.random() not random enough for security?

Math.random() is a pseudo-random generator that is deterministic and predictable if the internal state is known. Attackers can potentially reverse-engineer the state from output, making it unsafe for passwords or tokens. crypto.getRandomValues() uses a true random source (e.g., OS entropy) and is designed for security.

Can I use Math.random() to shuffle an array?

Yes, but use the Fisher–Yates shuffle, not sort(() => Math.random() - 0.5), which is biased and inefficient. The Fisher–Yates algorithm iterates backward and swaps each element with a random earlier one.

What is modulo bias and why does it matter?

Modulo bias occurs when you use Math.floor(Math.random() * range) and the range does not evenly divide the total number of possible random values. For example, if Math.random() returns one of 2^53 possible values, and your range is 3, the residues 0 and 1 occur slightly more often than 2. For most non-security uses, the bias is negligible, but for cryptographic purposes it is unacceptable.

How do I generate a random number without Math.random()?

You can use crypto.getRandomValues() for secure randomness, or implement your own PRNG like the LCG shown above. For a simple non-secure alternative, you could use Date.now() or performance.now() as a seed, but those are not truly random and often produce poor distributions.

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.