Because Math.random is built to be fast and statistically uniform, not unpredictable.
The spec's whole requirement is a Number in [0, 1), "chosen randomly or pseudo randomly with approximately uniform distribution", using an implementation-defined algorithm, plus distinct sequences for distinct realms. It says nothing about seeding quality or predictability, so no security property can be relied on.
In practice engines use a small, fast pseudo-random generator. In V8 it's xorshift128+ (since V8 4.9, Chrome 49): 128 bits of state that pass statistical tests, but the V8 team states it "is still not cryptographically secure". Its output is a deterministic function of a small internal state, and it isn't designed to stop someone who has seen earlier outputs from working out that state and the values that follow. In V8 you can even see the determinism directly: the --random-seed flag fixes the seed and replays the same sequence.
That matters wherever a value must be unguessable: session IDs, password-reset and CSRF tokens, invite codes, API keys, one-time codes, nonces. Use a CSPRNG (cryptographically secure pseudo-random number generator) instead:
crypto.getRandomValues(typedArray)from the Web Crypto API fills an integer typed array (up to 65,536 bytes) with cryptographically strong values. It works in browsers, workers and Node.js.crypto.randomUUID()returns a random version 4 UUID. In browsers it's limited to secure contexts (HTTPS).- In Node.js,
crypto.randomInt(min, max)returns an integer in [min, max) without modulo bias, andcrypto.randomBytesreturns aBuffer.
Math.random remains fine for things that aren't secrets: shuffling a demo playlist, jitter in retry back-off, sampling, games without stakes.