How to Generate a Random Number in JavaScript (With Code Examples)

Learn the most common patterns for generating random numbers in JavaScript, including integers, ranges, and secure random values.

Random numbers show up everywhere in JavaScript projects: games, simulations, A/B testing, data visualization, password generators, and test data. This guide walks through how to generate random numbers in JavaScript, from basic Math.random() usage to secure and advanced techniques.

Understanding Math.random()

In JavaScript the usual starting point is Math.random(), which returns a floating point number in the range [0, 1). That means the value can be 0 but will never reach 1, which matters when you scale it to other ranges.

Generating Random Floating Point Numbers

To generate a random floating point number between two values you can scale and shift that base value, for example random = Math.random() * (max - min) + min, and optionally round it to a fixed number of decimal places with Number.toFixed or Math.round.

function getRandomFloat(min, max, decimals = 2) {
  const value = Math.random() * (max - min) + min;
  return Number(value.toFixed(decimals));
}

// Example: a random float between 1.5 and 5.5 with two decimals
const randomFloat = getRandomFloat(1.5, 5.5, 2);
console.log(randomFloat);

Generating Random Integers

A very common helper is getRandomInt(min, max), which returns an integer between min and max inclusive. This is the building block for most integer-based random operations.

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

// Example: a dice roll between 1 and 6
const diceRoll = getRandomInt(1, 6);
console.log(diceRoll);

With that helper you can easily build things like a dice roll getRandomInt(1, 6), or pick a random index in an array by calling getRandomInt(0, array.length - 1) and using it to look up array[randomIndex]. This is especially useful for picking random elements.

Random selection from arrays is one of the most common use cases: you compute a random index from 0 to array.length - 1 and then return array[index]. This pattern powers random tips, quote rotators, and simple loot tables.

function getRandomArrayElement(items) {
  if (!items.length) return undefined;
  const index = getRandomInt(0, items.length - 1);
  return items[index];
}

const colors = ['red', 'green', 'blue', 'yellow'];
const randomColor = getRandomArrayElement(colors);
console.log(randomColor);

Creative Uses: Random Hex Colors and Passwords

Other classic examples include random color generators and simple password generators. A random hex color can be built by repeatedly choosing a random character from the string '0123456789ABCDEF', while a password generator loops over a larger character set.

function getRandomHexColor() {
  const alphabet = '0123456789ABCDEF';
  let color = '#';

  for (let index = 0; index < 6; index += 1) {
    const charIndex = getRandomInt(0, alphabet.length - 1);
    color += alphabet[charIndex];
  }

  return color;
}

console.log(getRandomHexColor());

For security-sensitive passwords, you should avoid Math.random() and use our secure random string generator instead.

Seeded Randomness and Unique Sequences

For testing and simulations you sometimes want randomness that is repeatable. A seeded random number generator produces the same sequence of values every time you start from the same seed, which makes debugging much easier.

class SeededRandom {
  constructor(seed) {
    this.seed = seed;
  }

  next() {
    this.seed = (this.seed * 9301 + 49297) % 233280;
    return this.seed / 233280;
  }

  nextInt(min, max) {
    return Math.floor(this.next() * (max - min + 1)) + min;
  }
}

const rng = new SeededRandom(12345);
console.log(rng.nextInt(1, 100));

When you need random numbers without duplicates, you can use a Set to track chosen values. For more advanced cases like UUID generation, specialized algorithms are often preferred.

Security Considerations

It is important to understand that Math.random() is not cryptographically secure. It is fine for UI effects, simple games, and simulations, but you should not use it to generate passwords, tokens, API keys, or anything security sensitive. For details on why this matters, read our dedicated article on secure random string generation.

For security critical code use cryptographically secure random number generators instead: crypto.getRandomValues() in the browser and crypto.randomBytes() in Node.js. These APIs are designed so their output is much harder to predict, which is essential for authentication and encryption.

Batch Generation and Performance

For performance sensitive workloads you can also generate random numbers in batches, for example by filling a typed array in a loop. This is useful when you need thousands of values for high-frequency visualizations or simulations.

function generateRandomNumberBatch(count, min = 0, max = 1) {
  const result = new Float32Array(count);

  for (let index = 0; index < count; index += 1) {
    result[index] = Math.random() * (max - min) + min;
  }

  return result;
}

console.log(generateRandomNumberBatch(5, 0, 100));

Whether you need a simple JavaScript random number generator or a complex security tool, understanding these core principles will help you build more robust applications.

Frequently Asked Questions

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

Use Math.floor(Math.random() * 10) + 1 to get a random integer from 1 to 10 inclusive.

Is Math.random() truly random?

In JavaScript, Math.random() is a pseudo-random number generator. It is not cryptographically secure but sufficient for most non-security use cases.

What is the range of Math.random()?

Math.random() returns a floating-point number from 0 (inclusive) to 1 (exclusive).

Try the JavaScript Random Number Generator

Experiment with different ranges, integer/float modes, and duplicate control directly in your browser, then copy the generated JavaScript snippets into your own project.

Open the JavaScript Random Number Generator tool