Generate Random Number in JS: Math.random() Explained

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(), for example: Math.floor(Math.random() * max) gives an integer from 0 up to (but not including) max. This is the core technique, but there are important nuances about distribution, security, and practical use that follow.

How Math.random() Works

Math.random() is a built-in JavaScript function that produces a pseudo-random number using an algorithm internal to the JavaScript engine (typically a variant of xorshift or Mersenne Twister). The returned value is a decimal with roughly 53 bits of randomness, meaning it can take about 9 quadrillion possible values between 0 and 1. The key characteristics:

  • Returns a floating-point number in the range [0, 1) — 0 is possible, 1 is never returned.
  • Is pseudo-random, not cryptographically secure — the sequence is deterministic if the seed is known.
  • Is fast and suitable for games, simulations, and general use, but not for security-sensitive applications.

Because the distribution is approximately uniform, each value in the range is equally likely, but the precision is finite, so very large ranges may have slight biases.

Generating Random Integers in a Range

The most common need is a random integer between two values. The standard formula is:

// Random integer from min (inclusive) to max (inclusive)
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}

Example: getRandomInt(1, 10) returns a number from 1 to 10. The Math.ceil and Math.floor ensure that if you pass decimals, the range is handled correctly. For a range excluding the max (like 0 to 9), use Math.floor(Math.random() * max).

For a random floating-point number in a range (e.g., between 5 and 10), use:

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

This returns a decimal like 7.3421.

Choosing the Right Approach

Your choice depends on what you need:

  • Simple random integer: Use Math.floor(Math.random() * range).
  • Inclusive range: Add 1 to the range in the multiplication.
  • Random element from an array: Use arr[Math.floor(Math.random() * arr.length)].
  • Cryptographically secure randomness: Use crypto.getRandomValues() (see below).
  • Seeded randomness for reproducible sequences: Implement a custom PRNG (e.g., mulberry32) because Math.random() cannot be seeded.

For most web development tasks, Math.random() is perfectly adequate. For anything involving passwords, tokens, or gambling, switch to the Web Crypto API.

Common Pitfalls and Misconceptions

One frequent mistake is using Math.round(Math.random() * max) to get an integer. This is wrong because Math.round makes the endpoints (0 and max) half as likely as the middle values, creating a biased distribution. Always use Math.floor.

Another misconception is that Math.random() is truly random. It is not; it is pseudo-random, meaning it is generated by a deterministic algorithm. For most purposes, this is fine, but if you need unpredictability (like for a lottery), it’s insufficient.

Also, note that Math.random() does not accept any arguments. Calling Math.random(10) still returns a number between 0 and 1; the argument is ignored.

Cryptographically Secure Random Numbers

For security-sensitive applications, use the Web Crypto API:

// Generate a secure random integer between 0 (inclusive) and max (exclusive)
function getSecureRandomInt(max) {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0] % max;
}

Note: The modulo method introduces a slight bias if max does not divide 2^32 exactly. For a perfectly unbiased method, use rejection sampling, but for most uses the bias is negligible. crypto.getRandomValues() is available in all modern browsers and in Node.js via the crypto module.

Practical Examples and Use Cases

Here are common real-world uses:

  • Dice roll: Math.floor(Math.random() * 6) + 1 gives 1–6.
  • Random password generation: Combine with a character set and a loop, but use crypto.getRandomValues for security.
  • Shuffling an array: Use the Fisher–Yates shuffle, which relies on random indices.
  • Random color: '#' + Math.floor(Math.random()*16777215).toString(16).
  • Random quote display: Pick a random index from an array of quotes.

For example, to simulate a coin flip:

const flip = Math.random() < 0.5 ? 'Heads' : 'Tails';

This works because Math.random() is uniformly distributed, so the probability of being less than 0.5 is exactly 50%.

Performance and Alternatives

Math.random() is extremely fast, typically taking less than a microsecond per call. If you need many random numbers (e.g., in a Monte Carlo simulation), it's efficient enough. However, if you need reproducible results (for testing or procedural generation), you'll want a seeded PRNG. A simple one is mulberry32:

function mulberry32(seed) {
return function() {
seed |= 0; seed = seed + 0x6D2B79F5 | 0;
let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
// Usage:
const rand = mulberry32(42);
console.log(rand()); // deterministic sequence

Alternatives include libraries like seedrandom for more robust seeded generation. For most non-cryptographic needs, Math.random() is the standard.

Frequently Asked Questions

Why does Math.random() not return 1?

By specification, Math.random() returns a number in the interval [0, 1) — that is, it can return 0 but never 1. This is to make it easier to scale to any range without hitting the upper bound accidentally.

How do I get a random number between two values inclusive?

Use the formula Math.floor(Math.random() * (max - min + 1)) + min. This includes both min and max. For example, getRandomInt(5, 10) can return 5, 6, 7, 8, 9, or 10.

Can I seed Math.random()?

No, the ECMAScript specification does not provide a way to seed Math.random(). To get a reproducible sequence, implement your own PRNG (like mulberry32 above) or use a library.

Is Math.random() safe for generating passwords?

No. Math.random() is not cryptographically secure; an attacker could potentially predict the output. Use crypto.getRandomValues() for any security-related randomness.

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, using the browser's entropy sources. Use crypto for anything that must be unpredictable.

How do I pick a random item from an array?

Use array[Math.floor(Math.random() * array.length)]. This works for any array, and the index is uniformly distributed between 0 and array.length - 1.

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.