Generate Random Number in Range JavaScript Math.random()
Learn how to generate random numbers in a specified range in JavaScript using Math.random(). Get random integers inclusive or exclusive, floats, and secure options with code examples for dice rolls and more.
How to generate a random number within a specified range in JavaScript?
What’s the best way to generate a random number in a specified range with JavaScript? For example, how can I get a random integer between 1 and 6 where the result could be any of these values: 1, 2, 3, 4, 5, or 6?
I need a JavaScript function that can generate random numbers within any custom range, not just between 0 and 1. What’s the standard approach for this common programming task?
Use Math.random() and scale its 0–1 output to your specified range: for floats use min + Math.random() * (max - min), and for a random integer between 1 and 6 (inclusive) use Math.floor(Math.random() * (6 - 1 + 1)) + 1 — commonly written Math.floor(Math.random() * 6) + 1. That pattern (scale, shift, then round appropriately) is the standard approach for generating JavaScript random numbers in any custom range; for security-sensitive randomness use the Web Crypto API instead.
Contents
- Math.random() basics
- Random float in a specified range
- Random integer (inclusive)
- Random integer (exclusive of max)
- Robust utility functions
- Common pitfalls and tips
- Cryptographically secure random numbers
- Sources
- Conclusion
Math.random() basics
Math.random() returns a pseudo-random floating‑point number x such that 0 ≤ x < 1. The MDN documentation for Math.random() explains that output is not cryptographically secure and is meant for typical randomness needs (games, sampling, UI effects, etc.).
Why does the 0–1 range matter? Because you scale that fraction to whatever interval you need. Multiply it to expand the span, then add an offset to shift it. Finally, if you need integers, use a rounding method that preserves uniformity (see below).
Random float in a specified range
To get a floating‑point number in [min, max) (min inclusive, max exclusive):
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
// example
getRandomFloat(1.5, 4.5); // possible values: 1.5 <= v < 4.5
This is the direct scaling of the 0 ≤ x < 1 output. For more discussion and edge cases for floats see the JavaScript.info explanation of random ranges.
If you need the max to be inclusive for floats, you can either use a tiny epsilon (not usually needed) or use a cryptographically secure method (see the crypto section).
Random integer (inclusive)
The standard, uniform way to get an integer between min and max inclusive is:
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// dice example
getRandomIntInclusive(1, 6); // returns 1, 2, 3, 4, 5, or 6
// shorthand for dice:
Math.floor(Math.random() * 6) + 1
Why the + 1? Multiplying by (max - min + 1) creates exactly as many integer slots as there are integers in the inclusive range; flooring then maps the scaled fraction into one of those slots uniformly. This formula and explanation are common across many references (for example, see W3Schools’ random page and short snippets like 30 Seconds of Code).
Random integer (exclusive of max)
If you want an integer in the half-open interval [min, max) (i.e., min inclusive, max exclusive), use:
function getRandomInt(min, max) {
// returns integer >= min and < max
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
// example: 1..5
getRandomInt(1, 6); // possible results: 1,2,3,4,5
This is useful when max is a length or an upper bound you don’t want included (arrays, zero-based indices, etc.).
Robust utility functions
Here are reusable helpers that handle swapped min/max and non-integer inputs gracefully:
// float in [min, max)
function randomFloat(min, max) {
min = Math.min(min, max);
max = Math.max(min, max); // ensure order
return Math.random() * (max - min) + min;
}
// integer in [min, max] inclusive (works if min/max are floats)
function randomIntInclusive(a, b) {
const min = Math.ceil(Math.min(a, b));
const max = Math.floor(Math.max(a, b));
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Examples:
randomIntInclusive(6, 1)still returns a value between 1 and 6.randomFloat(0.2, -1.5)will handle the swapped inputs and return between -1.5 and 0.2.
Common pitfalls and tips
- Off‑by‑one errors: forgetting
+ 1when you need the upper bound included is the most frequent bug. - Don’t use
Math.round()for integers. Why not?Math.round()biases the distribution because endpoints map unequally when rounding;Math.floor()(with the proper scale and offset) gives a uniform mapping. - Non-integer bounds: apply
Math.ceilto the lower bound andMath.floorto the upper bound when you want integer results. - Negative ranges work the same way — the formulas are agnostic to sign.
- Need reproducible sequences (for tests)? The built-in
Math.random()is not seedable in standard JS. Use a seeded PRNG library if determinism is required. For deeper background on the math and pitfalls, discussions like this Stack Overflow thread cover many practical points: Generating random whole numbers in JavaScript in a specific range and primers like SitePoint’s guide.
Cryptographically secure random numbers
Math.random() is fine for games and UI, but not for security-sensitive tokens, keys, or anything adversarial. Use the Web Crypto API in browsers:
// uniform float in [min, max) using crypto.getRandomValues()
function cryptoRandomFloat(min = 0, max = 1) {
const array = new Uint32Array(1);
crypto.getRandomValues(array);
const fraction = array[0] / 0x100000000; // 2^32
return fraction * (max - min) + min;
}
For unbiased secure integers, use rejection sampling to avoid modulo bias:
function cryptoRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
const range = max - min + 1;
const maxUint32 = 0x100000000; // 2^32
const limit = Math.floor(maxUint32 / range) * range;
const rand = new Uint32Array(1);
while (true) {
crypto.getRandomValues(rand);
if (rand[0] < limit) {
return min + (rand[0] % range);
}
// otherwise try again
}
}
The MDN Math.random() docs note crypto.getRandomValues() as the browser API for cryptographic randomness.
Sources
- Math.random() - JavaScript | MDN
- https://javascript.info/task/random-min-max
- https://javascript.info/task/random-int-min-max
- JavaScript Random - W3Schools
- Generate a random number or integer in a range - 30 Seconds of Code
- Generating random whole numbers in JavaScript in a specific range - Stack Overflow
- Generating Random Numbers in JavaScript with Math.random() - SitePoint
- Generate a random number in a range in JavaScript - Josh W. Comeau
Conclusion
In short: to generate a JavaScript random number in a specified range, scale and shift Math.random() — min + Math.random() * (max - min) for floats, and Math.floor(Math.random() * (max - min + 1)) + min for inclusive integers (e.g., Math.floor(Math.random() * 6) + 1 for a 1–6 die). Use robust helper functions to handle swapped bounds and non-integer inputs, and switch to the Web Crypto API (crypto.getRandomValues()) when you need cryptographically secure randomness.