-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Random values play an important role in many JavaScript applications. From generating OTPs and game scores to shuffling data, showing random quotes, selecting winners, or creating unpredictable animations, randomness makes applications dynamic and engaging. JavaScript provides a built-in way to generate random numbers using the Math.random() method, which is part of the Math object.
In this chapter, you will learn what JavaScript Random is, how Math.random() works, how to generate random numbers within a range, practical real-world examples, common mistakes, best practices, and how random numbers are used in everyday applications.
Math.random() is a built-in JavaScript method that returns a random floating-point number between 0 (inclusive) and 1 (exclusive).
This means:
The value can be 0
The value will always be less than 1
The value includes decimal points
let randomValue = Math.random();
console.log(randomValue);
Each time you run this code, you will get a different number. This randomness is what makes the method useful.
Random numbers help you:
Create games and quizzes
Generate OTPs and verification codes
Randomize questions or options
Pick random users or items
Simulate real-world uncertainty
Add variation to UI animations
Without randomness, applications would behave the same way every time, which reduces user engagement.
The value returned by Math.random() looks like this:
0.23456789123
0.87923411234
0.05678342198
These values are always:
Greater than or equal to 0
Less than 1
Different on each execution
Since the output is a decimal, you often need to combine Math.random() with other Math methods to get useful results.
Most real-world applications need random whole numbers instead of decimals. To do this, you combine Math.random() with methods like Math.floor().
let randomDigit = Math.floor(Math.random() * 10);
console.log(randomDigit);
This is useful for things like OTP digits or game scores.
let randomNumber = Math.floor(Math.random() * 10) + 1;
console.log(randomNumber);
Adding 1 shifts the range so it starts from 1 instead of 0.
A common requirement is generating a random number between a minimum and maximum value.
Math.floor(Math.random() * (max - min + 1)) + min
let min = 50;
let max = 100;
let randomMarks = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomMarks);
This approach is widely used in grading systems, games, and simulations.
let questions = [
"What is JavaScript?",
"What is a variable?",
"What is a function?",
"What is an array?"
];
let randomIndex = Math.floor(Math.random() * questions.length);
console.log(questions[randomIndex]);
This ensures a different question appears each time.
let diceRoll = Math.floor(Math.random() * 6) + 1;
console.log(diceRoll);
This simulates rolling a six-sided dice, commonly used in games.
let otp = Math.floor(Math.random() * 900000) + 100000;
console.log(otp);
This generates a six-digit OTP, often used in authentication systems.
let students = ["Ananya", "Riya", "Kavya", "Pooja", "Sneha"];
let randomStudent = students[Math.floor(Math.random() * students.length)];
console.log(randomStudent);
This can be used in classrooms or online quizzes.
let discount = Math.floor(Math.random() * 31) + 10;
console.log(discount + "%");
This gives a random discount between 10% and 40%.
Random numbers are often used with arrays to shuffle or select items.
let colors = ["Red", "Blue", "Green", "Yellow"];
let randomColor = colors[Math.floor(Math.random() * colors.length)];
console.log(randomColor);
This is useful for themes, backgrounds, or visual effects.
let names = ["Aarti", "Meera", "Nisha", "Ishita"];
names.sort(() => Math.random() - 0.5);
console.log(names);
This creates a randomized order, often used in games or quizzes.
Sometimes you need a random true or false value.
let isWinner = Math.random() > 0.5;
console.log(isWinner);
This can be used in decision-making logic or simulations.
Developers often make small mistakes when working with random numbers:
Expecting Math.random() to return whole numbers
Forgetting to use Math.floor() or Math.ceil()
Using incorrect range formulas
Assuming random values are truly unpredictable
Reusing the same random value when a new one is required
Understanding these mistakes helps avoid unexpected behavior.
To use random numbers effectively:
Always define the range clearly
Use Math.floor() for integer values
Avoid hardcoding values when ranges can change
Generate new random values when needed
Test your logic with multiple runs
Good practices make random-based features more reliable.
JavaScript Random is commonly used in:
Online games and puzzles
Quiz and test platforms
OTP and verification systems
Randomized UI effects
Marketing offers and discounts
Simulations and experiments
Almost every interactive web application uses randomness in some form.
The Math.random() method is a simple yet powerful tool in JavaScript. It allows you to generate unpredictable values that make applications dynamic and engaging. By combining Math.random() with other Math methods, you can generate random integers, work within specific ranges, select random array elements, and build real-world features like games, OTP systems, and quizzes. Understanding how randomness works and applying it correctly helps you create smarter and more interactive JavaScript applications.
Q1. How do you generate a random floating-point number between 0 and 1 using Math?
Q2. How do you create a random integer between 0 and 9 using Math.random() and Math.floor()?
Q3. How do you generate a random number between 1 and 100 using a custom function?
Q4. What is the purpose of Math.floor() in the expression Math.floor(Math.random() * 10)?
Q5. How do you generate a random floating-point number between 5.5 and 10.5?
Q6. Write a function that returns a random number between any two given integers, inclusive.
Q7. What happens if you forget to add +min when generating a random number in a custom range?
Q8. How do you create a random number generator for a dice roll (1 to 6)?
Q9. How do you ensure that the result of Math.random() never equals 1?
Q10. How can you generate a random number that simulates a coin toss (Head or Tail)?
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
