Math.random() generates a floating-point, pseudo-random number in the range $0$ (inclusive) up to but not including $1$ (exclusive). For cryptographic or security-critical applications, use crypto.getRandomValues().
flowchart TD
RandomReq["Random Number Requirement"] --> Security{"Security-Critical? (Passwords, Tokens, Keys)"}
Security -- "No (Games, UI Demos)" --> MathRand["Math.random() (Fast Pseudorandom PRNG)"]
Security -- "Yes (Auth Tokens, Crypto)" --> CryptoRand["window.crypto.getRandomValues() (CSPRNG)"]
| Feature | Math.random() |
crypto.getRandomValues() |
|---|---|---|
| Random Range | Float $0 \le x < 1$ | Populates typed array buffer with random bytes. |
| Predictability | Predictable (Non-cryptographic PRNG) | Cryptographically Secure (CSPRNG) |
| Performance | Extremely Fast | Slightly higher CPU overhead |
| Primary Use Case | Shuffling UI lists, casual games. | Password generation, UUIDs, security tokens. |
// Demonstrating Math.random() integer utility and Cryptographic Randomness
// 1. Helper Function: Random Integer between Min (inclusive) and Max (inclusive)
function getRandomIntInclusive(min, max) {
const minCeiled = Math.ceil(min);
const maxFloored = Math.floor(max);
return Math.floor(Math.random() * (maxFloored - minCeiled + 1)) + minCeiled;
}
console.log("--- Pseudorandom Dice Roll (1 to 6) ---");
for (let i = 0; i < 5; i++) {
console.log(`Roll #${i + 1}: ${getRandomIntInclusive(1, 6)}`);
}
// 2. Cryptographically Secure Random Token Generation (Web Crypto API)
function generateSecureToken(byteLength = 16) {
const array = new Uint8Array(byteLength);
crypto.getRandomValues(array);
// Convert bytes to hex string
return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
console.log("
--- Cryptographically Secure Token ---");
console.log(`Generated Token: ${generateSecureToken(16)}`);
Math.random() for Security: Do NOT use Math.random() to generate authentication tokens, password reset links, or session IDs.min and max limits in integer generation, always use Math.floor(Math.random() * (max - min + 1)) + min.globalThis.crypto.getRandomValues().Write a function getRandomArrayElement(arr) that uses Math.random() to select and return a random item from any array.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.