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.

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.

Here is the simplest way to see Math.random() in action:

// Random floating point between 0 (inclusive) and 1 (exclusive)
const random = Math.random();
console.log(random);

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);

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].

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, simple loot tables, and feature flag experiments.

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);

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 of letters, digits, and symbols to assemble a random string of a chosen length.

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());
function generatePassword(length = 12) {
  const charset =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
  let password = '';

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

  return password;
}

console.log(generatePassword(12));

For testing and simulations you sometimes want randomness that is repeatable. A seeded random number generator, often implemented as a small linear congruential generator (LCG) class, produces the same sequence of values every time you start from the same seed, which makes debugging and regression tests 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 keep track of previously used values in a Set or array and retry until you find a new one, or generate all numbers in the range first and then shuffle them. This works well when the range is not extremely large compared to the amount of numbers you need.

function getUniqueRandomNumbers(min, max, count) {
  if (count > max - min + 1) {
    throw new Error('Requested count is larger than the available range');
  }

  const values = new Set();

  while (values.size < count) {
    const candidate = getRandomInt(min, max);
    values.add(candidate);
  }

  return Array.from(values);
}

console.log(getUniqueRandomNumbers(1, 50, 5));

In many real-world systems some outcomes should be more likely than others, such as loot rarities in a game. A simple weighted random helper takes an array of weights, sums them, draws a random value between 0 and that sum, and then walks through the weights until it finds which bucket the random value falls into.

function weightedRandomIndex(weights) {
  const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
  const threshold = Math.random() * totalWeight;

  let runningTotal = 0;

  for (let index = 0; index < weights.length; index += 1) {
    runningTotal += weights[index];
    if (threshold <= runningTotal) {
      return index;
    }
  }

  return weights.length - 1;
}

const rarities = ['Common', 'Rare', 'Epic'];
const weights = [0.1, 0.3, 0.6];
console.log(rarities[weightedRandomIndex(weights)]);

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 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, encryption, and secret tokens.

Here is a simple example of generating a secure random integer in the browser:

function getCryptoSecureRandomInt(min, max) {
  const range = max - min + 1;
  const buffer = new Uint32Array(1);

  window.crypto.getRandomValues(buffer);
  return min + (buffer[0] % range);
}

console.log(getCryptoSecureRandomInt(1, 100));

Common patterns built on top of these APIs include generating random booleans with Math.random() < 0.5, generating random numeric identifiers with a fixed number of digits by choosing an appropriate min and max, or producing batches of random numbers up front to improve performance in tight loops.

function getRandomBoolean() {
  return Math.random() < 0.5;
}

console.log(getRandomBoolean());

function getRandomNumberWithDigits(digits) {
  const min = 10 ** (digits - 1);
  const max = 10 ** digits - 1;
  return getRandomInt(min, max);
}

console.log(getRandomNumberWithDigits(4));

For performance sensitive workloads you can also generate random numbers in batches, for example by filling a typed array in a loop or by precomputing a buffer of random values that your algorithm consumes over time instead of calling Math.random() on every single step.

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));

If you want to skip the boilerplate and experiment interactively with many of these patterns, you can use the JavaScript Random Number Generator tool on jsgenerator.com at https://jsgenerator.com/tools/javascript-random-number-generator, which lets you tweak ranges and modes and then copy production ready snippets directly into your project.

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