Math.random for Random Number Generation
You'll learn how to generate pseudo-random decimal numbers in JavaScript, the starting point for all randomization tasks.
What Is Math.random()?
Math.random() is JavaScript's built-in function for generating pseudo-random numbers. Every time you call it, it returns a floating-point number greater than or equal to 0 and strictly less than 1 (so 0 ≤ result < 1).
Think of it like spinning a roulette wheel that lands on a decimal between 0 and 0.999999... Each spin is unpredictable, though technically it follows a deterministic algorithm (hence "pseudo-random").
Basic Usage
console.log(Math.random()); // Example: 0.4721839502...
console.log(Math.random()); // Example: 0.8932674103...
console.log(Math.random()); // Example: 0.1234567890...
Each call produces a different number. You never get exactly 1, but you might get 0.
Why Start with 0–1?
This range is the foundation for all other random operations. Once you have a decimal between 0 and 1, you can scale it to any range you need:
// Random number between 0 and 10
const scaled = Math.random() * 10;
console.log(scaled); // Example: 7.239482...
// Random integer between 1 and 6 (dice roll)
const diceRoll = Math.floor(Math.random() * 6) + 1;
console.log(diceRoll); // Example: 4
You multiply by your desired range, then use rounding methods (Math.floor, Math.ceil, Math.round) to convert to integers when needed.
Important Notes
Math.random()takes no arguments- It's not cryptographically secure (don't use for passwords or tokens)
- Results are evenly distributed across the 0–1 range
Key Takeaway: Math.random() generates a pseudo-random decimal between 0 (inclusive) and 1 (exclusive), serving as the building block for all randomization in JavaScript.