JavaScript Get Random Number: Math.random() Explained

How-to basics · Updated November 23, 2026

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

How Math.random() Works Under the Hood

Math.random() is a built-in JavaScript function that generates a pseudo-random number. The value is a decimal between 0 (included) and 1 (not included), meaning it can return 0 but never exactly 1. The algorithm used is implementation-dependent—modern browsers typically use a variant of the xorshift128+ or similar PRNG (pseudo-random number generator) that is fast and has a long period, but it is not cryptographically secure.

Because it’s pseudo-random, the sequence is deterministic based on an internal seed. You cannot set the seed manually in standard JavaScript, which means you cannot reproduce the same sequence for testing. For most applications like games, UI shuffles, or simple sampling, this is perfectly fine.

Generating Random Integers in a Range

The most common task is getting a random integer between a minimum and maximum value (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;
}

Here’s why it works: Math.random() gives a value from 0 to just under 1. Multiplying by (max - min + 1) scales it to a range from 0 to just under the count of possible integers. Then Math.floor() rounds down to a whole number, and adding min shifts it to the desired start. For example, getRandomInt(1, 10) returns an integer from 1 to 10, each with equal probability.

If you want a random integer from 0 to a maximum (exclusive), you can use Math.floor(Math.random() * max). This is common for array indexing: array[Math.floor(Math.random() * array.length)] picks a random element.

Random Floating-Point Numbers

Sometimes you need a random decimal, not an integer. For a float between two values (inclusive of the lower bound, exclusive of the upper), use:

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

For example, getRandomFloat(5, 10) returns a number like 7.234 or 9.999, but never exactly 10. If you need to round to a certain number of decimal places, combine with .toFixed() but remember it returns a string, so convert back with Number() if needed.

Common Pitfalls and Misconceptions

A frequent mistake is using Math.round(Math.random() * max) to get an integer. That produces a non-uniform distribution because rounding treats endpoints differently—0 and max have half the probability of other values. Always use Math.floor() for uniform integers.

Another misconception is that Math.random() can return 1. It cannot; the upper bound is exclusive. This is why the formula adds 1 in the range calculation.

Also, don’t use Math.random() for anything security-related like generating passwords or tokens. Since it’s not cryptographically secure, an attacker could potentially predict the output. Use the Web Crypto API’s crypto.getRandomValues() instead.

Cryptographically Secure Random Numbers

For security-sensitive applications, use crypto.getRandomValues(). It generates true random numbers using the browser’s entropy sources. To get a random integer in a range securely, you can use:

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

This rejection sampling avoids modulo bias. The loop runs until the random value falls below the largest multiple of the range, ensuring each number is equally likely. Note that crypto.getRandomValues() is available in all modern browsers and in Node.js via the crypto module.

Practical Examples: Shuffling and Sampling

Random numbers are often used to shuffle arrays. A simple Fisher-Yates shuffle uses a random index:

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

To pick a random element from an array, you can use array[Math.floor(Math.random() * array.length)]. For multiple unique elements, you can shuffle a copy and take the first N.

Another use is generating a random hex color for visual effects:

const color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0');

This creates a value from 0 to 16777215, converts to hex, and pads with zeros to ensure six digits.

Performance and Alternatives

Math.random() is extremely fast—typically under a microsecond per call. For most use cases, performance is not a concern. However, if you need many random numbers in a tight loop, consider generating a batch at once using an array, or use a seeded PRNG like Mulberry32 if you need reproducibility.

For statistical simulations, you might want a normal distribution. You can use the Box-Muller transform:

function randomNormal() {
  let u = 0, v = 0;
  while (u === 0) u = Math.random();
  while (v === 0) v = Math.random();
  return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
}

This returns a value with mean 0 and standard deviation 1. You can then scale and shift it as needed.

Frequently Asked Questions

How do I get 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.999, Math.floor makes it 0–9, and + 1 shifts to 1–10.

Why does Math.random() not return 1?

By specification, Math.random() returns a number in the range [0, 1), meaning 0 is included but 1 is excluded. This ensures that when you multiply by a range, you never get the upper bound exactly, which simplifies uniform integer generation.

Can I seed Math.random() to get the same sequence?

No, the ECMAScript specification does not allow setting a seed for Math.random(). If you need reproducible randomness, implement a seeded PRNG like mulberry32 or use a library such as seedrandom.

Is Math.random() safe for passwords or tokens?

No. Math.random() is not cryptographically secure, meaning its output could be predicted if the internal state is known. Use crypto.getRandomValues() for any security-related random data.

How do I get a random element from an array?

Use array[Math.floor(Math.random() * array.length)]. This picks a random index from 0 to length-1. If the array is empty, it returns undefined, so check length first.

What is the difference between Math.floor and Math.round in random numbers?

Math.floor rounds down, giving a uniform distribution when used with Math.random(). Math.round rounds to the nearest integer, which makes the first and last values half as likely as the middle ones, creating bias. Always use Math.floor for uniform integers.

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.