Generate a random number between two numbers in JavaScript
Beginner · 3 min read
Dice games, quiz apps that shuffle questions, "pick a random winner" buttons and test data all need a random whole number in a range, like 1 to 6. JavaScript only gives you one random tool, and turning it into a range has a small trap that is easy to miss. In this tutorial you will build the range correctly and prove it.
You will write randomBetween(min, max), which returns a whole number from min to max, including both ends. You need to know what a function is and how to multiply and add. The Math methods are explained below.
What Math.random gives you
Math.random() returns a decimal from 0 up to, but never including, 1. Each call gives a different value.
const r = Math.random();
console.log(r >= 0 && r < 1); // true
Something like 0.7281 or 0.0153. It can be 0, but it is never exactly 1. That last detail decides the whole formula.
Math.floor
Math.floor rounds down to the whole number below.
console.log(Math.floor(5.99)); // 5
console.log(Math.floor(5)); // 5
console.log(Math.floor(0.2)); // 0
Why you can't test one random number
If a function returns a random number, you can't say in advance what it should be. Instead you test things that must always be true: every result is in the range, every result is a whole number, and over many tries every value shows up.
Here is the exercise. Try it yourself first if you like, then follow the steps.
12 Get a random number in a range
easyProduce a random whole number between two bounds, inclusive of both. Show that the bounds really are reachable.
Stuck? Three hints, smallest first
- 1.
Math.random()gives 0 up to but never including 1. - 2. For an inclusive range you need
Math.floor(Math.random() * (max - min + 1)) + min. The+ 1is what includes the top. - 3. You cannot assert a random value, so assert the range and the distribution instead.
Step 1: stretch the range
Multiply Math.random() by 6 and you get a decimal from 0 up to, but not including, 6. Round it down and you get a whole number from 0 to 5.
const n = Math.floor(Math.random() * 6);
console.log(n >= 0 && n <= 5); // true
There are six possible values, 0, 1, 2, 3, 4 and 5. We want 1 to 6, so we shift them.
Step 2: the first try, and its bug
A natural first attempt is "multiply by the size of the gap, then add min". The gap between 1 and 6 is 6 - 1, which is 5:
function exclusiveOfMax(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
const wrong = new Set(Array.from({ length: 600 }, () => exclusiveOfMax(1, 6)));
console.log(wrong.has(6)); // false
Array.from({ length: 600 }, …) calls the function 600 times and collects the results. A Set keeps only one copy of each value, so it shows which values ever came up. In 600 rolls, 6 never appears. It can't: Math.random() * 5 is always below 5, so after rounding down and adding 1, the largest result is 5.
This bug is hard to spot by eye. A die that never shows 6 still looks random.
Step 3: add one
From 1 to 6 there are six values, not five. The count of values is max - min + 1. That + 1 is what lets max come up.
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Math.random() * 6 gives 0 to just under 6. Rounding down gives 0 to 5. Adding 1 gives 1 to 6.
Step 4: refuse a backwards range
If someone calls randomBetween(9, 2), the count is negative and the results make no sense. Throw an error instead, so the mistake shows up straight away:
function randomBetween(min, max) {
if (min > max) throw new RangeError(`min ${min} is above max ${max}`);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Step 5: prove it
Roll 600 times and check the properties that must hold.
const rolls = Array.from({ length: 600 }, () => randomBetween(1, 6));
const seen = new Set(rolls);
console.log(rolls.every((n) => n >= 1 && n <= 6)); // true
console.log(rolls.every(Number.isInteger)); // true
console.log(seen.size); // 6
every returns true only if the check passes for every item. seen.size is how many different values came up. Six means every face appeared, including 6.
The full solution
The complete answer has the correct function and the buggy one side by side. It prints the first ten rolls (these change every time you press Run), the values seen, and the values the buggy version produced, which never include 6.
function randomBetween(min, max) {
if (min > max) throw new RangeError(`min ${min} is above max ${max}`);
// The + 1 is what makes max reachable. Without it, max never appears.
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// The common wrong version, for comparison.
function exclusiveOfMax(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
const rolls = Array.from({ length: 600 }, () => randomBetween(1, 6));
const seen = new Set(rolls);
console.log('first ten rolls:', rolls.slice(0, 10).join(', '));
console.log('distinct values:', [...seen].sort().join(', '));
// Prove the wrong version never reaches the top of the range.
const wrong = new Set(Array.from({ length: 600 }, () => exclusiveOfMax(1, 6)));
console.log('the buggy version produced:', [...wrong].sort().join(', '));
Output
6 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 6 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('every roll is within the range', rolls.every((n) => n >= 1 && n <= 6), true);
test('every roll is a whole number', rolls.every(Number.isInteger), true);
test('all six faces appeared', seen.size, 6);
test('the top of the range is reachable', seen.has(6), true);
test('the buggy version never reaches 6', wrong.has(6), false);
test('min above max is refused', (() => { try { randomBetween(9, 2); return false; } catch { return true; } })(), true);
You cannot assert a random number, so assert the properties instead: every value in range, every value a whole number, and all six faces appearing across 600 rolls. The last one is the real content — the version without + 1 looks right and silently never returns the maximum, which is a bug you will not notice by eye.
Common mistakes
- Leaving out the
+ 1. The top of the range never comes up, and nothing looks wrong. - Using
Math.roundinstead ofMath.floor. The two end values come up only half as often as the others. - Testing a single random value. Test the range and that every value appears over many tries.
Try it yourself
- Write
rollDice(count)that returns an array ofcountrolls from 1 to 6. - Write
pickRandom(items)that returns a random item from an array. (Hint: the range is 0 toitems.length - 1.) - Roll 6,000 times and count how often each face comes up. Each should be near 1,000.