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.
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.
_10function randomInt(min, max) {_10 // Inclusive of both min and max_10 return Math.floor(Math.random() * (max - min + 1)) + min;_10}_10_10randomInt(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.
_10const colours = ['red', 'green', 'blue'];_10const 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.
_10function randomFloat(min, max) {_10 return Math.random() * (max - min) + min;_10}_10_10randomFloat(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.
_15function secureRandomInt(min, max) {_15 const range = max - min + 1;_15 const limit = Math.floor(2 ** 32 / range) * range;_15 const buffer = new Uint32Array(1);_15 let value;_15_15 do {_15 crypto.getRandomValues(buffer);_15 value = buffer[0];_15 } while (value >= limit);_15_15 return min + (value % range);_15}_15_15secureRandomInt(100000, 999999); // a six-digit code
In Node.js, randomInt from the node:crypto module does the same job for you.
_10import { randomInt } from 'node:crypto';_10_10randomInt(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.
_10const id = crypto.randomUUID();_10_10const bytes = crypto.getRandomValues(new Uint8Array(32));_10const token = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
Common pitfalls
#- Using Math.round.
Math.round(Math.random() * (max - min)) + minmakes the first and last values half as likely as the others. UseMath.floorwith the+ 1. - Off by one. Decide whether
maxis 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 % rangeon 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.randomcannot be seeded. For repeatable sequences in tests or procedural generation, use a small seeded generator from a library. - Large ranges. The
Math.randomhelper is accurate for ranges well insideNumber.MAX_SAFE_INTEGER. The secure helper above handles ranges up to about four billion.
Related reading
#Was this resource helpful?