Coding

JavaScript Random Number in a Range (Min to Max, Inclusive)

To get a random whole number from min to max, both included, use Math.floor(Math.random() * (max - min + 1)) + min. For a random number from 1 to 10 that is Math.floor(Math.random() * 10) + 1.

The version below wraps this in a function you can paste into any script or browser console:

function randomIntInclusive(min, max) {
  const low = Math.ceil(min);
  const high = Math.floor(max);
  return Math.floor(Math.random() * (high - low + 1)) + low;
}

randomIntInclusive(1, 6);   // a die roll: 1, 2, 3, 4, 5 or 6
randomIntInclusive(-5, 5);  // any integer from -5 to 5

It is the same pattern MDN gives in its Math.random() reference as getRandomIntInclusive(). The rest of this page explains why each part is there, so you can adapt it for an exclusive upper bound, negative numbers, decimals or picking from an array.

How Math.random() works

Math.random() takes no arguments. MDN describes its result as a floating-point, pseudo-random number that is greater than or equal to 0 and less than 1, with approximately uniform distribution over that range. "Less than 1" matters: you can get 0, you can get 0.9999999999999999, but you never get 1.

Everything else is scaling. You turn the interval from 0 up to 1 into the interval you want with multiplication and addition, then cut off the fraction if you need a whole number. Take a die roll as an example:

  1. Math.random() gives a value in the range 0 to just under 1, for example 0.7311.
  2. * 6 stretches it to 0 to just under 6, for example 4.3866.
  3. Math.floor(...) rounds down to a whole number from 0 to 5, here 4.
  4. + 1 shifts it to 1 through 6, here 5.

The number you multiply by is the count of possible outcomes, not the highest value. Six faces means multiplying by 6. That is where the + 1 in the general formula comes from: from min to max inclusive there are max - min + 1 outcomes. From 1 to 10 that is 10 outcomes. From 5 to 8 it is 4 outcomes (5, 6, 7, 8).

Random integer with the maximum excluded

Sometimes the upper bound should be excluded, for example when you want a valid index into an array of a given length. Then the count of outcomes is just max - min:

function randomInt(min, max) {
  const low = Math.ceil(min);
  const high = Math.floor(max);
  return Math.floor(Math.random() * (high - low)) + low;
}

randomInt(0, 10);  // 0 to 9, never 10

This matches MDN's getRandomInt(), which it describes as inclusive of the minimum and exclusive of the maximum. Pick one of the two conventions per project and name the functions so the difference is obvious. Mixing them is a classic off-by-one bug: an inclusive helper used where an exclusive one was expected hands you an index one past the end of the array, which reads as undefined.

Why the formula uses Math.floor and not Math.round

It is tempting to write Math.round(Math.random() * 5) + 1 for a die. It runs without errors and looks right, but the faces are not equally likely. Math.round rounds to the nearest integer, so the result is 0 only when the random value times 5 is below 0.5, and 5 only when it is 4.5 or above. Each of those two ends covers half the width of the values in between:

FaceMath.round(Math.random() * 5) + 1Math.floor(Math.random() * 6) + 1
1about 10%about 16.7%
2 to 5 (each)about 20%about 16.7%
6about 10%about 16.7%

These percentages come from the arithmetic: the interval from 0 to 1 is cut into 10 equal pieces of width 0.1 by the rounding boundaries, with the first and last piece half-width. They are not a measurement. Math.floor cuts the interval into equal slices, one per outcome, so each outcome gets the same probability.

Negative ranges and non-integer bounds

The formula works for negative numbers because min is added after the floor, not before. For randomIntInclusive(-5, 5) there are 5 - (-5) + 1 = 11 outcomes, the floor produces 0 through 10, and adding -5 shifts that to -5 through 5.

The one thing to know about negatives is that MDN documents Math.floor() as rounding toward negative infinity, so Math.floor(-45.95) is -46, not -45. Do not swap in Math.trunc or parseInt and expect the same results on negative values: they cut toward zero instead.

That is why the helpers call Math.ceil(min) and Math.floor(max) first. They shrink fractional bounds inward to the nearest whole numbers inside the range. With randomIntInclusive(1.5, 4.2) the bounds become 2 and 4, so you get 2, 3 or 4. Without that step, a fractional min would give results like 1.5 mixed with whole numbers, or whole numbers outside the range you meant. If you only ever pass integers, you can drop those two lines.

Random decimal number in a range

For a floating-point result, skip the floor. MDN's version is:

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

randomBetween(1.5, 2.5);  // example output: 2.0817...

The result is at least min and below max. To limit it to two decimal places, round the finished value, for example Number(randomBetween(1.5, 2.5).toFixed(2)). toFixed returns a string, so wrap it in Number if you need arithmetic afterwards. Rounding after the fact makes the very top value slightly possible, since a number like 2.4999 rounds to 2.50, so treat the upper bound as inclusive at that precision.

Pick a random item from an array

Use the exclusive-max pattern with the array length, since valid indexes run from 0 to length - 1:

const colors = ["red", "green", "blue", "amber"];
const pick = colors[Math.floor(Math.random() * colors.length)];

Because Math.random() is always below 1, the index is never equal to colors.length. An empty array gives Math.floor(0), index 0, and a result of undefined, so check the length first if the array can be empty.

Common mistakes

  • Forgetting the parentheses. Math.random() * max - min + 1 multiplies first and subtracts afterwards, which gives the wrong range. The range must be grouped: Math.random() * (max - min + 1).
  • Calling Math.random() twice. Writing Math.floor(Math.random() * 6) + Math.random(), or computing the range once and the offset from a second call, mixes two unrelated values. Call it once per number.
  • Off-by-one at the top. Multiplying by max - min and expecting max to be possible. It never is. Add 1 for an inclusive upper bound.
  • Truncating instead of flooring. Math.trunc and parseInt round toward zero, so they are not interchangeable with Math.floor once negative values are involved.
  • Expecting repeatable output. Every page load or script run gives a different sequence, and you cannot change that, as the next section explains.

Limits: no seed, not for security

MDN states that the implementation selects the initial seed for Math.random() and that the user cannot choose or reset it. So you cannot replay a sequence for a test or a reproducible game level with it. Use a small seeded generator you write or install for that.

MDN also warns that Math.random() does not provide cryptographically secure random numbers and must not be used for anything related to security. Passwords, session IDs, reset tokens and anything an attacker would profit from guessing need the Web Crypto API instead, specifically crypto.getRandomValues().

A secure version with crypto.getRandomValues

crypto.getRandomValues() fills an integer typed array in place. MDN lists the accepted types as the integer arrays from Int8Array through BigUint64Array and says it does not accept the float arrays. A single call may fill at most 65,536 bytes, otherwise it throws QuotaExceededError.

const buffer = new Uint32Array(1);
crypto.getRandomValues(buffer);
console.log(buffer[0]);  // a 32-bit unsigned integer, 0 to 4294967295

Turning that value into a number in a range with % range introduces a small bias unless the range divides 232 evenly, because the leftover values at the top make the lower results slightly more likely. For casual use the bias is tiny. For anything security-relevant, discard raw values at or above the largest multiple of the range that fits in 32 bits and draw again. For a die roll, 232 % 6 is 4, so only 4 of the 4,294,967,296 possible values would ever be rejected.

For ordinary tasks such as animations, sampling a list, a random greeting or a dice game, Math.random() with the formula above is the right tool, and it is faster and simpler.

Frequently asked questions

How do I get a random number between 1 and 10 in JavaScript?
Use Math.floor(Math.random() * 10) + 1. Math.random() returns a value from 0 up to but not including 1, multiplying by 10 gives 0 up to but not including 10, Math.floor drops the fraction to give 0 through 9, and adding 1 shifts that to 1 through 10.
Can Math.random() ever return exactly 1?
No. MDN documents the result as greater than or equal to 0 and less than 1. That is why Math.floor(Math.random() * n) is always a valid index from 0 to n - 1 and never n.
Why shouldn't I use Math.round to pick a random integer?
Math.round makes the smallest and largest values half as likely as the ones between them. For 1 to 6 built as Math.round(Math.random() * 5) + 1, the values 1 and 6 each come up about 10% of the time and 2 to 5 about 20% each. Math.floor gives every value the same chance.
Can I seed Math.random to get the same numbers every time?
No. MDN states that the implementation chooses the initial seed and that the user cannot choose or reset it. For a repeatable sequence you need your own seeded generator.
Is Math.random() safe for passwords or tokens?
No. MDN says Math.random() does not provide cryptographically secure random numbers and should not be used for anything related to security. Use crypto.getRandomValues() for those cases.

Sources