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.
Math.random() WorksMath.random() returns a floating-point, pseudo-random number in the range: $$0 \le \text{result} < 1$$
0 (inclusive).0.999999..., but NEVER returns 1!To transform that float into a useful integer range:
To generate a random integer between min and max (inclusive):
Let's build a practical script that simulates rolling two six-sided dice between Player 1 and Computer:
Combine Math.random() with array.length to select a random element:
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?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Math Object Basics | Selecting Elements: getElementById, querySelector |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.