---
title: "How do I generate a random number in a range in JavaScript?"
description: "Scale Math.random to get a random integer between a minimum and maximum, and switch to crypto.getRandomValues for anything security related, such as tokens or codes."
url: https://www.danny.engineering/answer/javascript/how-do-i-generate-a-random-number-in-a-range-in-javascript
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T20:30:00.000Z
tags: ["Javascript"]
---

# How do I generate a random number in a range in JavaScript?

## The short answer


`Math.random()` returns a decimal from 0 up to, but not including, 1. Multiply it by the size of your range, round down, and add the minimum. For anything security related, use `crypto.getRandomValues` instead, because `Math.random` is not designed to be unpredictable.


```javascript
function randomInt(min, max) {
  // Inclusive of both min and max
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

randomInt(1, 6); // a dice roll: 1, 2, 3, 4, 5 or 6
```


## Why it happens


There is no built-in "random number between a and b" function in JavaScript, so you build one from `Math.random()`. Its output covers the half-open range from 0 to 1, which means it can return 0 but never 1.


Multiplying by `max - min + 1` stretches that range to cover every whole number you want. `Math.floor` turns the decimal into an integer, and adding `min` shifts the result into place. The `+ 1` is what makes `max` reachable.


`Math.random` is a pseudo-random number generator. It is fast and fine for games, animations, sampling and shuffling a playlist. Its output can, in principle, be predicted by someone who sees enough values, so it must not be used for passwords, tokens, invite codes or anything an attacker might want to guess.


## How to fix it


### A random integer, inclusive


Use the helper above. If you only need `0` up to `n - 1`, for example a random array index, it gets simpler.


```javascript
const colours = ['red', 'green', 'blue'];
const pick = colours[Math.floor(Math.random() * colours.length)];
```


### A random decimal in a range


For a decimal, skip the rounding. This includes `min` but not `max`.


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

randomFloat(1.5, 2.5); // for example 2.0371...
```


### A secure random integer with crypto.getRandomValues


`crypto.getRandomValues` fills a typed array with cryptographically strong random values. It is available as a global in browsers and in current versions of Node.js. Use rejection sampling so that every number in the range is equally likely; a plain `%` on the raw value would favour the smaller numbers slightly.


```javascript
function secureRandomInt(min, max) {
  const range = max - min + 1;
  const limit = Math.floor(2 ** 32 / range) * range;
  const buffer = new Uint32Array(1);
  let value;

  do {
    crypto.getRandomValues(buffer);
    value = buffer[0];
  } while (value >= limit);

  return min + (value % range);
}

secureRandomInt(100000, 999999); // a six-digit code
```


In Node.js, `randomInt` from the `node:crypto` module does the same job for you.


```javascript
import { randomInt } from 'node:crypto';

randomInt(1, 7); // 1 to 6: the maximum is exclusive here
```


### Random IDs and tokens


For a unique identifier, use `crypto.randomUUID()` rather than building one from random numbers. For a token, generate random bytes and encode them.


```javascript
const id = crypto.randomUUID();

const bytes = crypto.getRandomValues(new Uint8Array(32));
const token = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
```


## Common pitfalls

- **Using Math.round.** `Math.round(Math.random() * (max - min)) + min` makes the first and last values half as likely as the others. Use `Math.floor` with the `+ 1`.
- **Off by one.** Decide whether `max` is included, write it in the function name or a comment, and test the edges.
- **Shuffling with sort.** `array.sort(() => Math.random() - 0.5)` gives a biased shuffle. Use the Fisher-Yates algorithm, which swaps each item with a random earlier one.
- **Modulo bias.** `value % range` on a random 32-bit number is slightly uneven unless the range divides 2 to the power 32 exactly. Rejection sampling, as above, removes the bias.
- **Expecting repeatable results.** `Math.random` cannot be seeded. For repeatable sequences in tests or procedural generation, use a small seeded generator from a library.
- **Large ranges.** The `Math.random` helper is accurate for ranges well inside `Number.MAX_SAFE_INTEGER`. The secure helper above handles ranges up to about four billion.

## Related reading

- [MDN: Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)
- [MDN: Crypto.getRandomValues()](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)
