Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

Math.random() Is Not Random Enough for Your Giveaway

Here's a claim that will split a room of JavaScript developers: Math.random() is not random enough for your giveaway. Half the room will say "it's fine, nobody's going to reverse-engineer a $20 gift card draw." The other

Here's a claim that will split a room of JavaScript developers: Math.random() is not random enough for your giveaway. Half the room will say "it's fine, nobody's going to reverse-engineer a $20 gift card draw." The other half will point out that Math.random() is a pseudorandom generator with an implementation-defined algorithm, not designed for security-sensitive use — and that the usual % max trick quietly skews the odds. Both sides are partly right, which is exactly why the choice of generator matters more than most giveaway hosts think.

I built a free Random Number Generator that uses the browser's Web Crypto API instead, and this post is the reasoning behind it — plus the code, so you can judge the claim yourself.

The two invisible flaws in the usual approach

Most quick "random picker" snippets look like this:

// The snippet everyone writes. It has two problems.
function pickWinner(count) {
  return Math.floor(Math.random() * count) + 1;
}

Flaw 1: the generator. Math.random() returns a pseudorandom double. The spec does not fix the algorithm, it is not seeded by you, and it is not designed for unpredictability. For shuffling a playlist or picking a placeholder avatar, that is genuinely fine. For a draw where someone wins something real, "probably unpredictable" is a weaker promise than you want to make to your entrants.

Flaw 2: the modulo bias. Math.floor(Math.random() * count) squeezes a large random space into a smaller range. When the range does not divide the source space evenly, some outcomes get a slightly larger slice than others. The skew is tiny per draw — and that is precisely why it survives code review. Nobody notices a 0.001% edge. But "fair" is a binary claim: either every number has the same probability, or it doesn't. A giveaway host who says "every entry had an equal chance" while running a biased mapping is making a claim their code cannot back up.

The fix: Web Crypto + rejection sampling

The browser already ships a cryptographic random source: crypto.getRandomValues(). The fix is to draw from it and reject out-of-range values instead of wrapping them:

// Unbiased integer in [min, max], using Web Crypto.
function secureRandomInt(min, max) {
  const range = max - min + 1;
  const maxUint32 = 0xffffffff;
  // Largest multiple of range that fits in 32 bits.
  const limit = Math.floor((maxUint32 + 1) / range) * range - 1;
  const buf = new Uint32Array(1);
  let value;
  do {
    crypto.getRandomValues(buf);
    value = buf[0];
  } while (value > limit); // reject, don't wrap — this kills modulo bias
  return min + (value % range);
}

The do...while loop is the whole trick. Values above limit are thrown away rather than mapped onto the range, so every integer keeps exactly the same probability. The expected number of retries is negligible for any sane range, and the loop terminates quickly in practice.

That is the same approach the ToolkitLoop generator uses, per its tool page: Web Crypto with rejection sampling, no Math.random(). It also represents allowed values as intervals instead of building a full array, which is why drawing from 1 to 1,000,000,000 doesn't freeze the page.

No repeats is not elimination — and the difference decides winners

Here is the API-design detail that trips up nearly every giveaway host, and the one I most want you to take away. Two modes sound identical and behave differently:

// No repeats: unique WITHIN one draw only.
draw({ min: 1, max: 100, count: 10, noRepeats: true });
// -> 10 different numbers. But the NEXT draw may repeat one.

// Elimination mode: each draw removes the value from the pool.
drawElimination({ min: 1, max: 100 }); // -> 42 (42 leaves the pool)
drawElimination({ min: 1, max: 100 }); // -> 17 (never 42 again, until reset)

If you draw third place, second place, then first place with plain "no repeats" and a fresh draw each time, the same entry can win twice. Your entrants will notice before you do. Elimination mode exists for exactly this shape of problem: one draw at a time, earlier draws removed until you reset the pool. It is the right mode for classroom picks, bingo-style draws, and tournament order too.

There is one more honest limit: you can generate at most as many unique numbers as the range contains. One hundred unique values from 1 to 100 is the ceiling — ask for more and the tool tells you to expand the range. A generator that silently repeated numbers instead would be lying about the draw.

When this is NOT enough

Honesty cuts both ways, and the tool page says it plainly: this is a neutral browser-side selection aid, not an independently audited or legally verifiable draw service. For a classroom pick, a community giveaway, or a Discord raffle, Web Crypto plus a screen recording is a strong, checkable story. For a regulated lottery or a draw with legal stakes, use an audited service with a verifiable paper trail. Knowing which side of that line you're on is part of running a fair draw.

Try it yourself

The tool is free, needs no signup, and runs entirely in your browser — your range, exclusions, and results are never uploaded. Try the Random Number Generator with Elimination mode on your next giveaway, and screen-record the draw so your entrants can see it happen.

So, back to the opening claim: is Math.random() fine for a casual giveaway, or is anything with a prize on the line worth the Web Crypto version? Where do you draw the line — and what would you tell an entrant who asked how the winner was picked? I'm genuinely curious where developers land on this one.

Disclosure: I built this tool. The Random Number Generator is free, runs entirely in your browser, and needs no signup.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.