Counting and tallying · Random
Math.random vs crypto.getRandomValues: which is random enough, and for what?

The tool for this guide: Open the random number generator
Math.random is fine for games, animations and casual picks. Use crypto.getRandomValues whenever anyone could gain by predicting the result: passwords, tokens, prize draws. Both are pseudo-random generators. The difference is that Math.random can be predicted from earlier outputs and getRandomValues is built to resist that.
The short answer: use Math.random when nobody gains, and crypto.getRandomValues when somebody could
Math.random() and crypto.getRandomValues() are both pseudo-random generators, so "which is truly random" is the wrong
question. The useful one is whether anyone could gain by predicting the next value. If a person could win a prize, guess a
token or beat a game by knowing what comes next, use crypto.getRandomValues. If not, such as for a shuffle animation, a
dice game among friends or a random greeting, Math.random is statistically fair and simpler.
| What you are making | Could anyone gain by predicting it? | Use |
|---|---|---|
| Password, token, session or reset code, key | Yes, directly | crypto.getRandomValues |
| Prize draw, raffle, giveaway, wager, lottery | Yes, and people may doubt the result | crypto.getRandomValues |
| Dice, coin or card game with stakes | Yes, if a player can run or watch the code | crypto.getRandomValues |
| Animation, particles, shuffled greeting, test data | No | Math.random |
| Casual pick among friends | Not meaningfully | Math.random, or either |
| Simulation that must repeat exactly | Not applicable: you need a seed | A seeded generator, not Math.random |
What each function actually promises
Reading the specifications shows how little Math.random promises. The ECMAScript specification says it returns a Number
"greater than or equal to +0 but strictly less than 1, chosen randomly or pseudo randomly with approximately uniform
distribution over that range, using an implementation-defined algorithm or strategy", and adds that each realm must
produce a distinct sequence (ECMAScript, Math.random). Nothing
about secrecy, seeding or the algorithm is required. MDN adds that the seed is chosen by the engine and "cannot be chosen
or reset by the user" (MDN, Math.random).
The Web Cryptography specification promises more: "The getRandomValues method generates cryptographically strong random
values", and a call asking for more than 65,536 bytes throws a QuotaExceededError
(W3C, Web Cryptography API).
| Math.random() | crypto.getRandomValues() | |
|---|---|---|
| Returns | One decimal from 0 up to, not including, 1 | Fills an integer typed array with random bytes |
| Quality promised | "Approximately uniform", algorithm implementation-defined | "Cryptographically strong" |
| Seed | Chosen by the engine; cannot be set or reset | Taken by the engine from platform entropy |
| Size limit | None | 65,536 bytes per call |
| Secure context needed | No | No: the only Crypto member usable without one |
| Security use | MDN: "do not use them for anything related to security" | The method MDN recommends instead |
| Speed | Faster | Slower: the V8 team notes it costs more performance |
Both are pseudo-random; what differs is whether the output gives the next value away
crypto.getRandomValues is not a physical noise source. MDN states that implementations "are not using a truly random
number generator, but they are using a pseudo-random number generator seeded with a value with enough entropy", and that
the Web Cryptography specification mandates no minimum degree of entropy
(MDN, Crypto.getRandomValues()). So
"true random against pseudo-random" does not separate the two. A cryptographically strong generator is one where seeing any
amount of its output does not let you work out the next value or the seed, and that is the property Math.random lacks.
In V8, the engine behind Chrome and Node, Math.random uses a generator called xorshift128+: 128 bits of internal state, a
period of 2^128 − 1, and a pass on all the TestU01 statistical tests. It replaced an older generator that returned only
2^32 different values and failed many of those tests (V8 blog, "There's Math.random(), and then there's Math.random()").
The same post says it is "still not cryptographically secure".
The practical meaning is that statistical quality and security are separate. xorshift128+ is excellent on the first and poor on the second, because a generator with 128 bits of state can be solved for those bits. One public write-up recovers the full state from 20 outputs of 8 bits each, 160 bits against 128 bits of state, by solving a system of linear equations, and can then reproduce later values (GitHub gist, state recovery without z3). This is one write-up, not a standard, and what it needs is raw outputs. A page that reveals only a single winner leaks almost nothing. Tokens, identifiers, nonces and anything printed or returned from an API do leak.
Math.random is not biased. The remainder operator is.
The common worry that Math.random gives unfair picks is wrong for the generator, and right for a habit around it. A pick
among n entries needs a whole number, and the usual shortcuts are Math.floor(Math.random() * n) and
value % n. The first keeps the bias negligible because the generator offers about 2^52 distinct values. The second is
unfair when the value comes from a small range, such as one random byte of 256 values, which do not divide evenly by most n.
| Pick one of | One random byte, % n | 32-bit value, % n | 52-bit value (a double's best case) |
|---|---|---|---|
| 6 | +0.78% | +0.0000000466% | +0.0000000000000444% |
| 10 | +1.56% | +0.0000000931% | +0.0000000000000888% |
| 100 | +17.19% | +0.0000000931% | +0.0000000000000888% |
The last two columns assume every one of the 2^32 or 2^52 values is equally likely, which is the best a generator of that width can do. They are the figures behind the claim that the source is not what makes a pick unfair: 256 divides by 6 with a remainder of 4, so faces 1 to 4 each get 43 byte values and faces 5 and 6 get 42, a 16.80% against 16.41% chance. For one of 100, the first 56 entries get 3 of 256 values and the other 44 get 2.
The numbers also show a trap in the "use crypto" advice. Calling getRandomValues and then taking a byte modulo 100 is
less fair than Math.floor(Math.random() * 100). The source is secure and the mapping is biased. A secure source does not
fix an unfair mapping.
How to turn random bits into a fair pick
Rejection sampling removes the bias: throw away the draws that would favour some values, and redraw. For a range of n, find the largest multiple of n that fits in the draw, and redraw whenever the draw is at or above it.
js
function randomBelow(n) { // a whole number from 0 up to n - 1, 1 <= n <= 2**32
const limit = Math.floor(2 ** 32 / n) * n;
const buf = new Uint32Array(1);
do { crypto.getRandomValues(buf); } while (buf[0] >= limit);
return buf[0] % n;
}
Run on 600,000 draws of one of 6, every face came up between 99,675 and 100,411 times against 100,000 expected; on 1,000,000 draws of one of 100, every entry came up between 9,742 and 10,230 times against 10,000 expected. Both spreads are what chance gives. The code redraws about once in a billion draws for a range of 6 and once in 45 million for a range of 100, so the cost is invisible. The random number generator works the same rule through with a table for any range.
A shuffle needs the same care. The Fisher–Yates shuffle
swaps each position with a random earlier one, and each of those draws should use an unbiased
randomBelow. The guide to how many times to shuffle a deck covers the
physical side.
When Math.random is the wrong tool even though nobody is attacking
Math.random cannot be seeded, so it cannot repeat a sequence. A simulation that must reproduce a result, a procedurally
generated level or a test that needs the same "random" input every run needs a generator with a seed you control. Neither
function in this guide offers one. The seed of Math.random is chosen by the engine, and two realms, such as two frames
of a page, must produce different sequences.
The other case is one where being believed matters. A prize draw, a classroom pick or a team selection can be accurate and
still be questioned. Saying which source drew the result, and writing it where it can be checked, answers the question
before it is asked. On any page that runs in your browser and is not minified, you can search its script for
Math.random and getRandomValues and see which it uses.
What Simple Online Counter's random tools use
Simple Online Counter is a free set of counters, calculators and converters that run in the browser. Its random tools, the
random number generator, the coin flip, the
dice roller and the yes or no generator, draw every result from
crypto.getRandomValues and never call Math.random. A coin flip takes the last bit of one random byte, which splits
256 values exactly 128 and 128 and so needs no correction. Ranges use rejection sampling.
For a casual flip the difference from Math.random is invisible, and that is the point of stating it: the tool can be
defended without argument. The same source is why the coin flip's section on real coins
can say how a thrown coin differs from a drawn one. For testing whether a physical die matches a fair one, see
how to test whether a die is fair.
Sources
Each source was opened and checked on 22 November 2026.
- ECMAScript Language Specification, Math.random (section 21.3.2.28)
- MDN Web Docs, Math.random()
- MDN Web Docs, Crypto: getRandomValues() method
- W3C, Web Cryptography API, getRandomValues
- V8 blog, There's Math.random(), and then there's Math.random()
- GitHub gist, recovering V8 Math.random state without z3 (secondary source)
- Wikipedia, Fisher–Yates shuffle
Frequently asked questions
Is Math.random() truly random?
No. It is a pseudo-random generator: a fixed algorithm that stretches a hidden starting value into numbers that look uniform. The ECMAScript spec says only that the result is "chosen randomly or pseudo randomly" by an implementation-defined algorithm. V8 uses xorshift128+, with 128 bits of state, which passes the TestU01 statistical tests but is not secure.
Is Math.random() secure?
No. MDN says it "does not provide cryptographically secure random numbers" and should not be used for anything related to security. Its output is determined by a 128-bit internal state in V8, and published write-ups recover that state from about twenty observed outputs. Use crypto.getRandomValues for passwords, tokens and keys.
What is the difference between Math.random and crypto.getRandomValues?
Math.random returns one decimal in the range 0 up to but not including 1, from an algorithm the engine chooses, with no security promise. getRandomValues fills an integer array with cryptographically strong bytes, up to 65,536 per call. Both are pseudo-random, but only the second is designed so that earlier output does not reveal later output.
Is crypto.getRandomValues truly random?
Not in the physical sense. MDN says implementations use a pseudo-random generator seeded with a value that has enough entropy, often taken from the operating system. What makes it different is that the generator is cryptographically strong, so seeing its output does not let anyone work out the next value or the seed.
Can Math.random be predicted?
In V8, yes, once enough output has been seen. Its generator, xorshift128+, has 128 bits of state, and a public write-up recovers that state from 20 outputs of 8 bits each, about 160 bits, by solving linear equations. After that every later value is known. The attacker needs the raw outputs, which a single drawn winner does not reveal.
Is Math.random good enough for a raffle or random name picker?
For an informal pick among friends, yes: its output is statistically fair. For a draw with real prizes, or where people could doubt the result, use crypto.getRandomValues and say so on the page. The cost is nothing a visitor can feel, and the stated method can then be checked by reading the page's script.
Is Math.random biased?
Not noticeably. A 52-bit result leaves the most likely value of a 1-in-100 pick about 1 part in 1,100 trillion above its fair share. The bias that matters comes from using the remainder operator on too small a number: a random byte taken modulo 100 gives 56 of 100 entries a 1.17% chance and the other 44 a 0.78% chance.
How do I get a random integer in a range with crypto.getRandomValues?
Draw a 32-bit value, work out the largest multiple of the range that fits in 2^32, redraw if the value is at or above it, and only then take the remainder. This is rejection sampling, and it leaves every value in the range with exactly the same chance. Taking the remainder of a single draw without the redraw favours the low values.
People also search for
More in counting and tallying
Count to 1,023 on your fingersThe value of each of ten fingers, worked examples, how to count up, and why the top is 1,023.Updated · 8 min read
The gambler's fallacy and coin-flip streaksA streak of heads never makes tails due. The exact odds, how long a run to expect, the 1913 roulette run, what asylum judges and umpires did, and when a streak is real evidence.Published · 10 min read
How to read reversed tarot cardsBlocked, weaker, too far or opposite: four readings of the same reversed card, how to pick one and stay with it, and the exact odds of reversals in a 3 or 10-card spread.Published · 7 min read
How to test whether a die is fairThe chi-square test in four steps with a worked example, the 5% limit for a d4 to a d100, and the part most guides skip, how many rolls it takes to catch a die that really is loaded.Published · 10 min read
Is a coin flip really 50/50?A hand-flipped coin landed on the side it started on 50.8% of the time over 350,757 flips. The figures, why the bias is real but small, and the one fix the authors give.Published · 11 min read
How to tally survey responses by handA worked tally of 60 paper forms, from the sheet to the percentages. Blank answers, two boxes ticked, tick-all questions, write-ins, and the check that proves the count.Updated · 21 min read