Generating Random Integers with Math.random
You'll learn how to transform Math.random's decimal output into useful random integers within any range you need.
The Challenge with Math.random
As you learned previously, Math.random() generates a random decimal between 0 (inclusive) and 1 (exclusive). But often you need whole numbers—like simulating a dice roll (1-6) or picking a random array index. That's where combining Math.random() with Math.floor() becomes essential.
The Formula
Think of Math.random() as giving you a random point on a ruler. To get integers, you need to:
- Stretch the ruler by multiplying by your desired range
- Round down with
Math.floor()to get whole numbers
The pattern is:
Math.floor(Math.random() * max) // 0 to max-1
For a range starting at a number other than zero:
Math.floor(Math.random() * (max - min + 1)) + min // min to max (inclusive)
Practical Examples
// Random integer 0-9
const digit = Math.floor(Math.random() * 10);
// Dice roll: 1-6
const diceRoll = Math.floor(Math.random() * 6) + 1;
// Random between 50-100
const score = Math.floor(Math.random() * 51) + 50;
// (51 possibilities: 50,51,52...100)
Why Math.floor?
You might wonder why not Math.round() or Math.ceil()? Math.floor() ensures even distribution. With Math.round(), the boundary numbers (like 0 and your max) would appear half as often as middle values.
Key Takeaway: Combine Math.floor(Math.random() * range) to generate random integers, adding an offset when you need a minimum value greater than zero.