The core of JavaScript randomness is the built-in object Math
and its function, Math.random()
. In this easy-to-follow tutorial, I explain everything you need to know to generate random numbers with Vanilla JavaScript.
In this tutorial:
- Base function: Math.random()
- Rounding: Math.floor()
- Adjusting the range
- Application example: Dice Game
- FAQ
Generating random numbers with Math.random()
The function Math.random()
generates a random floating-point number (a number with a decimal) between 0 and 1.
const randNum = Math.random();
- Range: 0 to 0.99999999…
- Example output: 0.4589274…
This is a great start, but it’s not a whole number (integer), and the range is too small for many applications.
Rounding the Number with Math.floor
The following code is a concise and standard method for generating a random integer within a specific range, a fundamental concept in programming.
const max = 10; // To generate a random integer from 0 to 9
const randInt = Math.floor(Math.random() * max);
It is designed to produce a whole number from 0 up to (but not including) the value of max
. In our example, it generates a random integer from 0 to 9.
Code | Explanation |
---|---|
const max = 10; | Declares a constant variable max with a value of 10. This defines the limit of your random number range. |
Math.random() | Generates a random floating-point number between 0 (inclusive) and 1 (exclusive). (e.g., 0.783... ) |
* max | Multiplies the random result by max (10). This scales the number to be between 0 and 10 (exclusive). (e.g., 7.83... ) |
Math.floor(…) | Rounds the number down to the nearest whole integer. This eliminates the decimal and ensures the number is a whole integer. |
const randInt = … | Stores the final whole number (the random integer) in the variable randInt . |
Because Math.random()
can be a number slightly less than 1 (like 0.999...
), when you multiply it by 10, the largest possible result is 9.999...
.
The Math.floor()
function then ensures the maximum integer output is 9 and the minimum integer output is 0.
Math.random() | *10 | Math.floor() | |
---|---|---|---|
Min | .000… | 0 | 0 |
Max | .999… | 9.99… | 9 |
Shifting the Random Number Range
The following code calculates the size of the desired range, generates a random number within that size, and shifts the result up to start at the correct minimum value.
const min = 1;
const max = 6; // To get a random integer from 1 to 6
const randomIntegerInRange = Math.floor(Math.random() * (max - min + 1)) + min;
Code | Explanation |
---|---|
const min = 1; | Sets the minimum possible value (the bottom of the range). |
const max = 6; | Sets the maximum possible value (the top of the range). |
Math.random() * (max – min + 1) | Range Size: The expression (max - min + 1) calculates the total number of possible results. For 1 to 6, this is (6 - 1 + 1) = 6 . 2. Scaling: Multiplying Math.random() (which is 0 to 0.999…) by 6 produces a random number from 0 to 5.999… |
Math.floor(…) | Rounds Down: This removes the decimal part and converts the result to a whole integer, giving a number from 0 to 5. |
+ min | Shifts the Range: Adding the min value (1) to the result shifts the entire range up one spot. This finalizes the random integer to be between 1 and 6. |
Random Number Application: JavaScript Dice Game
Random numbers are commonly used in gaming. In my next tutorial, How to Make a JavaScript Dice Game, we generate random numbers from 1 to 6. Join my Patreon army to get early access!
// Array containing the alt text for dice images
const side_alt = ["roll: 1", "roll: 2", "roll: 3", "roll: 4", "roll: 5", "roll: 6"];
// Function fires when the player clicks on the play button
function throwdice(){
// Min and max range
const min = 1;
const max = 6;
// Generate random numbers between 1 and 6
const randFormula = () => Math.floor(Math.random() * (max - min + 1)) + min;
let rand1 = randFormula();
let rand2 = randFormula();
let rand3 = randFormula();
let rand4 = randFormula();
// Set Image src
document.getElementById("mydice1").src = "images/d" + rand1 + ".png";
document.getElementById("mydice2").src = "images/d" + rand2 + ".png";
document.getElementById("hisdice1").src = "images/e" + rand3 + ".png";
document.getElementById("hisdice2").src = "images/e" + rand4 + ".png";
// Set Image alt
document.getElementById("mydice1").alt = side_alt[rand1 - 1];
document.getElementById("mydice2").alt = side_alt[rand2 - 1];
document.getElementById("hisdice1").alt = side_alt[rand3 - 1];
document.getElementById("hisdice2").alt = side_alt[rand4 - 1];
who_won(rand1,rand2,rand3,rand4);
}
function who_won(rand1,rand2,rand3,rand4){
let player_points = rand1 + rand2;
let enemy_points = rand3 + rand4;
let giffy = winner(player_points,enemy_points);
document.getElementById("message").src = "images/" + giffy;
document.getElementById("message").alt = giffy;
document.getElementById("enemy_points").innerHTML = `Enemy Score: ${enemy_points}`;
document.getElementById("player_points").innerHTML = `Your Score: ${player_points}`;
}
function winner(player, enemy) {
if (player < enemy) {
return "loser.gif";
} else if (player > enemy) { // Use else if for better logic flow
return "win.gif"
} else { // If not less than and not greater than, it must be equal
return "tie.gif"
}
}
Also, stay up-to-date by subscribing to my blog and following me on Facebook and X.
FAQ: JavaScript Random Number Generation
1. Why is the result of Math.random()
called “pseudo-random”?
The term “pseudo-random” means “not truly random.” Computers cannot generate true randomness because they must follow a fixed set of instructions (an algorithm). However, for all general coding purposes (e.g., gaming, web sites) the output is unpredictable enough to be reliable.
Math.random()
uses a very complex algorithm to simulate randomness. While the results are predictable if you know the exact algorithm and starting conditions, the output is unpredictable enough to be considered a reliable random number. Don’t worry about the “pseudo” part—it’s standard terminology across all major programming languages.
2. Why do you use const
and let
instead of var
for variables?
Using const
and let
helps you structure cleaner, more professional code that is easier to maintain.
You may see older JavaScript code that uses the var
keyword for everything. However, the modern standard is to use const
and let
because they improve code predictability and help prevent errors.
const
(Constant): This is used for variables whose value should never change after they are defined (like yourside_alt
array or yourmin
andmax
values). This is generally the safest default choice.let
(Lettable): This is used for variables whose value is expected to change (like yourplayer_points
score or variables used inside a loop).
3. How does JavaScript know which element to change (e.g., the dice images or the scores)?
JavaScript uses unique identifiers, specifically the id
attribute in your HTML, to locate and manipulate elements on the page. This is known as interacting with the DOM (Document Object Model).
- In your HTML, every element the JavaScript needs to change has a unique ID:
- The player’s dice have IDs like
mydice1
. - The score paragraphs have IDs like
player_points
.
- The player’s dice have IDs like
- In your JavaScript, the core command
document.getElementById("mydice1")
finds that exact element. - Once found, JavaScript changes a property of that element, such as its image path (
.src
), its text (.innerHTML
), or its description (.alt
).
This system of using unique IDs is the foundation for all dynamic interactivity on the web.
Meet the Author: Shelly Selzer

Hi, I’m Shelly Selzer—a technical writer from South Georgia with a soft spot for clean code and clear communication. I write tutorials that make complex topics feel like child’s play.
If you like learning by example, you’ll feel right at home here—I share practical JavaScript tricks, writing insights, and the occasional behind-the-scenes post about life as a writer-developer hybrid.
📬 Stay in the loop: Subscribe to this blog
💼 Contact me: Contact Shelly Selzer
☕ Support my work: Join My Patreon Army