Understanding Randomness in Web Development
Math.random() versus crypto.getRandomValues(): how each generator works, which one to use for tokens, passwords and raffles, and how to shuffle without modulo bias.
When building web applications, we often need random numbers. Whether it's for generating unique IDs, shuffling arrays, creating games, or implementing security features, randomness plays a crucial role. But not all randomness is created equal.
Pseudo-Random Numbers: Math.random()
The most common way to generate random numbers in JavaScript is using Math.random(). This function returns a floating-point number between 0 (inclusive) and 1 (exclusive).
// Generate a random number between 0 and 1
const random = Math.random(); // e.g., 0.7342891023
// Generate a random integer between 1 and 10
const randomInt = Math.floor(Math.random() * 10) + 1;
How Does It Work?
Math.random() uses a Pseudo-Random Number Generator (PRNG). V8 (Chrome, Node.js), SpiderMonkey (Firefox) and JavaScriptCore (Safari) all use xorshift128+, which keeps 128 bits of internal state. The specification does not name an algorithm, so this can change between engine versions.
The key characteristic of PRNGs is that they are deterministic. Given the same initial seed value, they will always produce the same sequence of numbers. This is why they're called "pseudo" random - they appear random but are actually computed from a mathematical formula.
// Conceptually, PRNGs work like this:
let seed = Date.now();
function pseudoRandom() {
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
return seed / 0x7fffffff;
}
Pros and Cons of Pseudo-Random
Pros:
- Fast and efficient
- A seeded PRNG you write yourself, like the one above, is reproducible, which helps with tests and replayable games.
Math.random()itself cannot be seeded. - Works in all browsers
Cons:
- Predictable if the seed is known
- Not suitable for cryptographic purposes
- An observer who sees a few dozen outputs can recover the 128-bit state and predict every later value
Cryptographically Secure Random Numbers: Crypto API
For security-sensitive applications, JavaScript provides the Web Crypto API with crypto.getRandomValues(). This function generates cryptographically secure random numbers.
// Generate cryptographically secure random values
const array = new Uint32Array(1);
crypto.getRandomValues(array);
const secureRandom = array[0];
// Generate a secure random number between 0 and 1
function secureRandomFloat() {
const array = new Uint32Array(1);
crypto.getRandomValues(array);
return array[0] / (0xffffffff + 1);
}
How Does It Work?
The Crypto API uses a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG). It is still an algorithm, not a source of physical randomness, but it is designed so that its outputs cannot be predicted. Browsers take their randomness from the operating system's CSPRNG, which the OS seeds from unpredictable sources:
- Hardware events (mouse movements, keyboard timings)
- System noise
- CPU timing variations
- Hardware random number generators (when available)
Modern computers often have dedicated hardware for generating random numbers, like Intel's RDRAND instruction.
Pros and Cons of a CSPRNG
Pros:
- Unpredictable and secure
- Suitable for cryptographic operations
- Observed outputs do not reveal earlier or later ones
Cons:
- Slightly slower than Math.random()
- Returns at most 65,536 bytes per call; larger requests throw a
QuotaExceededError - Overkill for non-security use cases
When to Use Which?
| Use Case | Recommended Method |
|---|---|
| Games and animations | Math.random() |
| Shuffling playlists | Math.random() |
| UI randomization | Math.random() |
| Token generation | crypto.getRandomValues() |
| Password generation | crypto.getRandomValues() |
| Session IDs | crypto.getRandomValues() |
| Lottery/raffles | crypto.getRandomValues() |
| Encryption keys | crypto.getRandomValues() |
A generated password is a run of such draws: 16 characters from an 86-symbol alphabet carry about 103 bits.
A Practical Example: Fair Lottery Drawing
For applications like lottery drawings or raffles where fairness matters, you should always use cryptographically secure randomness. Here's a simple implementation:
// Uniform integer in [0, n). Plain `x % n` favours small values whenever
// 2^32 is not a multiple of n, so redraw the values above the last full block.
function secureRandomInt(n) {
const limit = Math.floor(0x100000000 / n) * n;
const buf = new Uint32Array(1);
do {
crypto.getRandomValues(buf);
} while (buf[0] >= limit);
return buf[0] % n;
}
function secureShuffle(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = secureRandomInt(i + 1);
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
function drawWinners(participants, count) {
const shuffled = secureShuffle(participants);
return shuffled.slice(0, count);
}
With 32-bit draws and n = 100, plain x % 100 makes four outcomes each about 2.2 × 10⁻¹⁰ less likely than the rest, a gap no χ² test on a d100 can detect.
This ensures that:
- The selection cannot be predicted
- The selection cannot be manipulated
- Every participant has an equal chance
Conclusion
Knowing the difference between Math.random() and a CSPRNG is essential for building secure and reliable web applications. Use Math.random() for non-critical randomness, and always reach for crypto.getRandomValues() when security or fairness matters.
Want to try secure randomness in action? The Random Name Picker draws names with crypto.getRandomValues().