Math.random for Random Number Generation
What you'll learn: How to generate random decimal numbers in JavaScript using Math.random().
What Is Math.random?
Math.random() is a method that generates a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). Think of it like spinning a dial that can land anywhere from exactly zero up to — but never quite reaching — one.
Every time you call Math.random(), you get a different unpredictable decimal value:
Math.random(); // might return 0.4387290384
Math.random(); // might return 0.9182736451
Math.random(); // might return 0.0000123456
The Range: [0, 1)
The result is always >= 0 and < 1. You'll never get exactly 1, but you can get exactly 0 (though extremely rarely). The notation [0, 1) means "including 0, excluding 1."
const randomValue = Math.random();
console.log(randomValue); // something like 0.7234891234
Common Use: Random Integers
While Math.random() gives you decimals, you often want whole numbers. Combine it with Math.floor to get random integers:
// Random integer from 0 to 9
const randomDigit = Math.floor(Math.random() * 10);
// Random integer from 1 to 6 (like a dice roll)
const diceRoll = Math.floor(Math.random() * 6) + 1;
The pattern: multiply by your range size, floor it, then add your starting number.
Why "Pseudo-Random"?
The numbers appear random but are generated by an algorithm, not true randomness. For games and simulations, this is perfectly fine. (True randomness requires special hardware.)
Key Takeaway: Math.random() returns a random decimal between 0 (inclusive) and 1 (exclusive) — scale and round it to generate random integers.