How Computers Generate Random Numbers (and When It Matters)
The difference between Math.random() and crypto.getRandomValues(), when a seeded generator is what you want, how modulo bias creeps into passwords, and which ID formats are truly random.
A computer that runs the same program twice with the same inputs is supposed to produce the same output twice. That determinism is the whole point of a CPU. So the phrase "computer-generated random number" is, taken literally, a contradiction. What computers actually do is run an algorithm that produces a stream of numbers spread out enough to look random, or else reach outside the deterministic world entirely and sample physical noise the operating system has collected.
Which of those two things you get matters enormously. One of them is fine for shuffling a deck or rolling a die. The other is what stands between an attacker and your password. Picking the wrong one is one of the more common and more dangerous mistakes in web code, because the broken version still looks random when you eyeball the output. The bug never shows up in a screenshot.
This post covers the difference between Math.random() and the Web Crypto API, the cases where a predictable generator is exactly what you want, the modulo bias that creeps into "pick a random item from a list", and which popular ID formats are random at all.
Math.random() is a deterministic PRNG
Math.random() returns a floating-point number in the range [0, 1). Under the hood, every JavaScript engine implements it as a pseudorandom number generator (PRNG): a deterministic function that holds some internal state, returns a number derived from that state, then advances the state for next time. V8 (Chrome, Node) uses an algorithm called xorshift128+. Other engines use their own, but they share the same shape.
The "pseudo" part is the important word. A PRNG is seeded once, usually from some entropy the engine grabs at startup, and from then on the entire sequence is a pure function of that seed. If you knew the internal state and the algorithm, you could reproduce every "random" number the page will ever generate, in order. JavaScript gives you no way to read that state directly, but an attacker does not need one: xorshift128+ is simple enough that a few consecutive outputs let a constraint solver reconstruct the state, and public proof-of-concept tools do exactly that. This is why MDN's reference page for Math.random() tells you not to use it for anything related to security.
Two other things to know about Math.random():
- It is fast and has no setup cost. You call it, you get a number.
- The language specification promises very little: an approximately uniform value from an "implementation-defined algorithm or strategy." Modern engines are good enough that you will not see patterns by eye, and good enough for games, but nothing obliges them to be unpredictable to an adversary, and in practice they are not.
For a game, none of that matters. Predictability is a security concern, and a dice roll at the kitchen table has no secrets to protect.
The classic dice idiom
Rolling a die with Math.random() is the idiom every tutorial teaches:
function rollDie(sides) {
return Math.floor(Math.random() * sides) + 1;
}
Math.random() gives a float in [0, 1). Multiply by sides (say 6) and you get a float in [0, 6). Math.floor knocks it down to an integer in {0, 1, 2, 3, 4, 5}, and + 1 shifts that to {1, 2, 3, 4, 5, 6}. Each face is (very nearly) equally likely because the [0, 1) interval is being chopped into six equal slices.
The same generator is the right tool for throwaway values that only need to differ from one another:
const tempKey = Math.random().toString(36).slice(2, 11);
That produces a short alphanumeric label for telling list items apart within one page session. It does not need to be unguessable, only distinct enough, so a PRNG is a perfectly reasonable choice.
This is the healthy use of Math.random(): games, animations, jitter, picking a random tip to show, shuffling a playlist. Anywhere the cost of an attacker predicting the value is zero.
When predictable is the point: seeded generators
Determinism, the property that makes Math.random() unsafe for secrets, becomes a feature in the right setting. A seeded PRNG lets you choose the starting state, so the same seed always replays the same sequence. Simulations use this to make runs reproducible, test suites use it to make failures repeatable, and games use it for shareable level layouts or daily puzzles that come out identical for every player.
Math.random() cannot be seeded, but a seedable generator takes only a few lines. Mulberry32 is a popular small one:
function mulberry32(seed) {
let state = seed >>> 0;
return function next() {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rand = mulberry32(42);
rand(); // the same value every time you start from seed 42
Everything in there is arithmetic on a single 32-bit number: add a constant, scramble the bits, return a fraction. That is all a PRNG is. Its small state means the sequence repeats after about four billion values, which is plenty for a game and too short for heavy scientific work. It also means anyone who learns or guesses the seed can replay every output, so a seeded generator must never guard a secret.
The Loopaloo Dice Roller shows both modes. By default it rolls with the browser's cryptographic generator. Type a seed and it switches to a deterministic stream instead, so anyone who opens your shared link gets the same sequence of rolls, which is a handy way to settle an argument about a roll made online.
crypto.getRandomValues() is the secure one
When the output is a secret, you need a cryptographically secure pseudorandom number generator (CSPRNG). In the browser that is the Web Crypto API:
const array = new Uint32Array(16);
crypto.getRandomValues(array);
getRandomValues fills a typed array with values from a cryptographically secure generator that is seeded from the operating system's entropy source (on Linux, the getrandom system call; other platforms have their own equivalents). The defining property of a CSPRNG is that even an attacker who has seen a long run of past outputs cannot predict the next one with better than negligible advantage. That is a much stronger promise than "looks random," and it is the promise you need for passwords, tokens, session IDs, encryption keys, and password-reset links.
The tradeoffs versus Math.random():
Math.random() | crypto.getRandomValues() | |
|---|---|---|
| Type of generator | PRNG | CSPRNG |
| Predictable from past outputs | Yes, in practice | No (that is the guarantee) |
| Output | one float in [0, 1) | fills a typed integer array |
| Right for | games, shuffles, jitter, UI keys | passwords, tokens, keys, secrets |
| Throws on misuse | never | throws if you request too many bytes at once |
One sharp edge: getRandomValues has a per-call quota of 65,536 bytes. Ask for more in a single call and it throws a QuotaExceededError. For anything human-sized, like a 128-character password, you are nowhere near the limit.
Turning random numbers into a password
A password generator is the textbook case for Web Crypto. The usual first version allocates one random 32-bit integer per character and maps each onto the alphabet with %:
function makePassword(length, alphabet) {
const randomInts = new Uint32Array(length);
crypto.getRandomValues(randomInts);
let password = '';
for (const n of randomInts) {
password += alphabet[n % alphabet.length];
}
return password;
}
Because the source is a CSPRNG, an attacker who somehow saw your last ten generated passwords still learns nothing about the next one. The strength of the result is also easy to state exactly. Each character is an independent, uniform draw from an alphabet of size N, so the password carries length * log2(N) bits of entropy. Sixteen characters from the 94 printable ASCII symbols come to about 105 bits.
That figure describes the generator, not the string, and the distinction matters. A strength meter judging a password you typed has to infer the alphabet from the characters present, so it will happily score Password123! at around 79 bits because it contains all four character classes, even though it is among the first guesses any cracking tool tries. The formula only holds when every character really was an independent uniform draw, which is what a CSPRNG gives you, and only if the mapping onto the alphabet keeps the draws uniform. That last condition is where the % above causes trouble.
Modulo bias: the bug hiding in % alphabet.length
Picking a random item from a list is the most commonly botched step in this whole area. Look again at the mapping:
alphabet[n % alphabet.length]
n is a uniform random integer in [0, 2^32). The alphabet might have, say, 70 characters, and 2^32 is not a multiple of 70: it leaves a remainder of 46. So when you wrap the range around with %, the first 46 characters of the alphabet each get one extra chance that the last 24 do not. The low characters come up very slightly more often than the high ones. That is modulo bias.
Here is the effect at a tiny scale you can reason about by hand. Imagine your random source produces 0..9 (ten equally likely values) and you want a number 0..2 using % 3:
| Random value | % 3 |
|---|---|
| 0, 3, 6, 9 | 0 |
| 1, 4, 7 | 1 |
| 2, 5, 8 | 2 |
Value 0 comes up four times out of ten; values 1 and 2 only three times each. That is a 33% over-representation of one outcome. The reason is that 10 does not divide evenly by 3; the leftover (10 mod 3 = 1 value) spills onto the front of the range.
With a 32-bit source and a 70-character alphabet the bias is real but tiny: the favored characters are ahead by about one part in sixty million, which does not meaningfully dent the entropy of a human-length password. The bias grows as the range shrinks relative to the alphabet, though. Draw from single bytes instead (a Uint8Array, values 0 to 255) and the same alphabet becomes visibly lopsided. Since 256 is three times 70 plus 46, the first 46 characters get four chances in 256 and the last 24 get three, the same 33% skew as the toy example.
The textbook fix is rejection sampling: compute the largest multiple of the alphabet size that fits in your range, and if a draw lands above it, throw it away and draw again.
function unbiasedIndex(n) {
const max = Math.floor(2 ** 32 / n) * n; // largest clean multiple
const buf = new Uint32Array(1);
let x;
do {
crypto.getRandomValues(buf);
x = buf[0];
} while (x >= max); // reject the lopsided tail
return x % n; // now perfectly uniform
}
You discard a small fraction of draws in exchange for an exactly uniform result. Well-written token and ID libraries rely on the same idea (nanoid, for instance, masks and rejects rather than taking a raw modulo), and the cost is so small that there is rarely a reason to skip it, even when the bias would have been negligible.
The Loopaloo Password Generator draws every character this way, from crypto.getRandomValues with rejection sampling, and reports the entropy exactly as length times log2 of the alphabet size. Extra characters you add that are already in the set are counted once, because a character listed twice would be picked twice as often, and the page shows how many bits a "contain one of each class" rule costs. It also has a built-in check that draws 3,000 passwords and tests whether every character turns up equally often. The page is candid about that test's limit: a frequency test catches a lopsided alphabet, but it cannot tell a cryptographic generator from a predictable one. Math.random() would pass it too.
Which ID formats are actually random
Identifiers are where "is this random?" gets slippery, because many popular formats are only partly random and some are not random at all:
| Format | What is inside | Random bits |
|---|---|---|
| UUID v4 | Random bits plus fixed version and variant markers | 122 |
| UUID v7 | 48-bit Unix millisecond timestamp, then random bits | up to 74 |
| ULID | 48-bit millisecond timestamp, then randomness | 80 |
| UUID v1 / v6 | Timestamp, clock sequence, and node ID | little or none |
| UUID v3 / v5 | A hash of a namespace and a name | none: the same input always gives the same UUID |
| Snowflake | 41-bit timestamp, 10-bit machine ID, 12-bit sequence | none |
| NanoID | Random characters from a 64-symbol alphabet | 126 at the default 21 characters |
For a v4 UUID, crypto.randomUUID() in modern browsers and Node is the easy, safe route. Its random bits come from the same secure source as getRandomValues, with no hand-rolled bit-twiddling to get wrong.
The time-ordered formats are a deliberate trade. UUID v7, ULID, and Snowflake put a timestamp in the high bits so that IDs sort by creation time and index well in databases. Their value lies in ordering and collision avoidance, not secrecy. Anyone holding one can read off when it was created, and a Snowflake, with no random bits at all, can be enumerated outright: guess the millisecond, the machine, and a small sequence number and you have a valid ID. That is by design, not a flaw, as long as nobody treats the ID as a secret. For v7 and ULID the random tail should still come from a CSPRNG (the ULID spec asks for one where possible), so that IDs minted in the same millisecond cannot be predicted from one another.
The rule that follows: if an identifier must be unguessable (a session token, an unsubscribe link, an API key, a password-reset URL), use a v4 UUID or a token built directly from crypto.getRandomValues(), and never a timestamp-based format.
The Loopaloo UUID Generator makes these differences easy to see. It generates UUID versions 1, 3, 4, 5, 6, and 7 alongside ULID, NanoID, CUID2, and Snowflake IDs, takes its random bits from crypto.getRandomValues, and reads any of them back, so you can see the creation time hiding inside a v7 UUID, a ULID, or a Snowflake. Its uniformity check, like the password check, says plainly that passing proves an even distribution, not unpredictability, and for name-based UUIDs it reports that there is nothing to test.
A quick decision guide
The whole topic collapses to one question: what happens if someone predicts this number?
| If the value is... | Use | Because |
|---|---|---|
| A casual dice roll, shuffle, animation jitter | Math.random() | Prediction costs nothing; speed and simplicity win |
| A throwaway UI key or label | Math.random() | Only needs to be locally distinct |
| A reproducible simulation, test, or daily puzzle | A seeded PRNG | The same seed must replay the same sequence |
| A password, token, or key | crypto.getRandomValues() | Must be unpredictable to an attacker |
| A v4 UUID | crypto.randomUUID() | Crypto-backed and standard-compliant |
| A sortable ID where order is the point | A time-ordered format (UUID v7, ULID, Snowflake) | Ordering is the goal; treat the ID as public |
And one rule for mapping a random integer onto a range of size n: a raw % n introduces modulo bias whenever n does not divide the range evenly. The bias is usually tiny for small alphabets against a 32-bit range, but use rejection sampling when you need an exactly uniform result.
The reason any of this deserves attention is that the failure mode is invisible. A password built on Math.random() produces gibberish that looks every bit as strong as one built on a CSPRNG. The difference only surfaces the day someone with the right knowledge decides to predict it. Choosing the right generator up front is the cheapest security decision you will ever make, because it costs nothing and the code is no harder to write.
If you want to see these choices in practice, try Loopaloo's Dice Roller (cryptographic rolls by default, a reproducible stream when you give it a seed), the Password Generator (Web Crypto with rejection sampling and the entropy stated exactly), and the UUID Generator (crypto-backed v4 alongside time-ordered and name-based formats you can take apart).
Related Tools
Dice Roller
Roll dice in standard notation, from 2d6+3 to 4d6kh3 and advantage, with every die shown, the odds of each total before you roll, and seeded rolls anyone can repeat from a shared link.
Password Generator
Make random passwords in one click, with the strength in bits calculated from the settings and the time each would take to guess.
UUID Generator
Generate UUID v1 to v7, ULID, NanoID, CUID2 and Snowflake IDs in bulk, and inspect any ID to read its version and creation time.