Generating random numbers is one of the most common tasks in JavaScript—whether you are building games, quizzes, OTP systems, or randomized features.
In this post, you’ll learn exactly how to generate a random number between 1 and 100 using JavaScript, with examples and outputs.
🎯 The Simple Answer
JavaScript provides the built-in function:
Math.random()
This returns a random decimal between 0 (inclusive) and 1 (exclusive):
0.00023
0.89233
0.55555
To convert it into a number from 1 to 100, use:
Math.floor(Math.random() * 100) + 1;
✅ Example: Get a Random Number from 1 to 100
const randomNum = Math.floor(Math.random() * 100) + 1;
console.log(randomNum);
Sample Output
73
(Your number will be different every time.)
🔍 How It Works? (Step-by-Step)
1. Math.random()
Generates random values like:
0.12
0.98
0.45
2. Multiply by 100
0.45 * 100 = 45
0.98 * 100 = 98
3. Math.floor()
Removes decimals (round down):
45.67 → 45
98.12 → 98
4. Add +1
Because random numbers could be 0, we add 1 to shift the range from:
0–99 → 1–100
🔁 Generate and Print 10 Random Numbers (1–100)
for (let i = 0; i < 10; i++) {
console.log(Math.floor(Math.random() * 100) + 1);
}
Sample Output
18
77
9
42
100
13
65
2
88
50
✨ Bonus: Function to Easily Reuse Anywhere
function randomFrom1To100() {
return Math.floor(Math.random() * 100) + 1;
}
console.log(randomFrom1To100());
🎮 Practical Uses
You can use this method in:
✔ Games
Random enemies, damage points, levels.
✔ Quiz Apps
Random questions, random rewards.
✔ OTP / Token Generators
Random 2-digit numbers.
✔ Simulations
Random probability calculations.
🚀 Conclusion
To generate a random number between 1 and 100 in JavaScript, use:
Math.floor(Math.random() * 100) + 1;
It is simple, accurate, and used widely in real-world applications.
Discover more from Learners Store
Subscribe to get the latest posts sent to your email.