MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Random Numbers Example0%
Study Materials
JavaScript for BeginnersProgress 0%
1.1What is JavaScript?1.2How JavaScript Works in Browser1.3Setting up Environment: VSCode, Live Server
9.1Working with Date Object9.2Math Object Basics9.3Random Numbers Example
HomeTutorialsJavaScript for BeginnersRandom Numbers Example
Selecting Elements: getElementById, querySelector

Random Numbers Example

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

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 returns 1!
1console.log(Math.random()); // e.g. 0.428172948192
2console.log(Math.random()); // e.g. 0.892019482711

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$:

1// Random integer from 0 to 9:
2const rand0to9 = Math.floor(Math.random() * 10);

Formula 2: The Universal Min-Max Formula (Inclusive):

To generate a random integer between min and max (inclusive):

1function getRandomInt(min, max) {
2 // Enforce whole numbers:
3 min = Math.ceil(min);
4 max = Math.floor(max);
5 return Math.floor(Math.random() * (max - min + 1)) + min;
6}

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:

1function rollDie() {
2 // Returns integer between 1 and 6 inclusive
3 return Math.floor(Math.random() * 6) + 1;
4}
5 
6function playDiceGame() {
7 const playerRoll = rollDie();
8 const computerRoll = rollDie();
9 
10 console.log(`🎲 You rolled: ${playerRoll}`);
11 console.log(`🎲 Computer rolled: ${computerRoll}`);
12 
13 if (playerRoll > computerRoll) {
14 console.log("🏆 Victory! You won the round!");
15 } else if (computerRoll > playerRoll) {
16 console.log("💥 Defeat! The computer won this time.");
17 } else {
18 console.log("🤝 It's a draw! Roll again.");
19 }
20}
21 
22playDiceGame();

4. Picking a Random Item from an Array

Combine Math.random() with array.length to select a random element:

1const colors = ["Crimson", "RoyalBlue", "Emerald", "Gold", "Violet"];
2 
3function getRandomItem(arr) {
4 const randomIndex = Math.floor(Math.random() * arr.length);
5 return arr[randomIndex];
6}
7 
8console.log(`Lucky color: ${getRandomItem(colors)}`);

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the exact output range of Math.random() in JavaScript?
Question 2
What formula generates a random integer from 1 to 6 (like rolling a standard die)?
Question 3
How do you select a random element from an array const list = ["A", "B", "C", "D"]?
Question 4
Why is Math.floor() preferred over Math.round() when generating random integer ranges?
Question 5
What is the maximum value that Math.floor(Math.random() * 10) can return?
Next Lesson

Selecting Elements: getElementById, querySelector

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Math Object BasicsSelecting Elements: getElementById, querySelector

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Beginners with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext