Random Numbers Example
Generating Random Numbers and the Dice Game Example
Generating random numbers is crucial for games, unique ID generation, simulations, password generators, and lottery drawings. JavaScript provides Math.random() as its pseudo-random number generator.
1. How Math.random() Works
Math.random() returns a floating-point, pseudo-random number in the range: $$0 \le \text{result} < 1$$
- It can return
0(inclusive). - It approaches
0.999999..., but NEVER returns1!
2. Generating Random Integers in a Range
To transform that float into a useful integer range:
Formula 1: Random Integer from 0 to $N - 1$:
Formula 2: The Universal Min-Max Formula (Inclusive):
To generate a random integer between min and max (inclusive):
3. Hands-On Project: Two-Player Dice Game
Let's build a practical script that simulates rolling two six-sided dice between Player 1 and Computer:
4. Picking a Random Item from an Array
Combine Math.random() with array.length to select a random element:
Practice Quiz
Math.random() in JavaScript?const list = ["A", "B", "C", "D"]?Math.floor() preferred over Math.round() when generating random integer ranges?Math.floor(Math.random() * 10) can return?Selecting Elements: getElementById, querySelector
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Math Object Basics | Selecting Elements: getElementById, querySelector |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.