BuildUtilities

Randomness & Probability Guide

Types of Randomness

Not all "random" is equal. Understanding the difference matters, especially for security:

  • Pseudo-random (Math.random()): fast but predictable. Fine for games, UI, and simulations. NOT for security.
  • Cryptographically secure (crypto.getRandomValues()): unpredictable. Required for passwords, tokens, keys, and anything security-sensitive.

Random Numbers

// Random integer between min and max (inclusive)
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Cryptographically secure random
const array = new Uint32Array(1);
crypto.getRandomValues(array);
console.log(array[0]); // e.g., 3847291056

Dice Probability

Rolling multiple dice creates a bell curve distribution, middle values are more likely than extremes:

  • 1d6: flat distribution, each face equally likely (16.7%)
  • 2d6: 7 is the most common result (16.7%), while 2 and 12 are rare (2.8%)
  • 4d6 drop lowest: classic D&D stat generation, biased toward higher values (average ~12.2)

Entropy & Token Security

Entropy measures how unpredictable a value is, in bits. More entropy = harder to guess:

4-digit PIN:            ~13 bits   (easy to crack)
8-char alphanumeric:    ~48 bits   (moderate)
16-char mixed password: ~95 bits   (strong)
UUID v4:                ~122 bits  (very strong)
256-bit key:            256 bits   (cryptographic)

Random Pickers

Need to pick a random item from a list? The Fisher-Yates shuffle is the gold standard for unbiased selection:

// Pick one random item
const items = ["Alice", "Bob", "Charlie"];
const winner = items[Math.floor(Math.random() * items.length)];

Try our Random Number Generator, Dice Roller, or Random Picker to generate random values instantly.

FAQ

Is Math.random() truly random?

No, it's pseudo-random, generated by a deterministic algorithm. It's good enough for most non-security purposes but should never be used for passwords or tokens.

How long should a random token be?

For API keys and session tokens, 32+ characters of alphanumeric gives you ~190 bits of entropy, more than enough. For passwords, 16+ characters with mixed character types is excellent.

Try These Tools

Related Documentation

Tip Jar