JavaScript Random Numbers
Generate random numbers and create random behaviors in JavaScript
🎲 What is Math.random()?
Math.random() generates a random decimal number between 0 (inclusive) and 1 (exclusive). It's the foundation for creating all kinds of random behaviors in JavaScript.
// Basic random number (0 to 0.999...)
console.log(Math.random()); // Example: 0.7834592847362
Output:
0.7834592847362 (varies each time)
Common Random Patterns
Random Integer
Whole numbers in a range
// 1 to 10
Math.floor(Math.random() * 10) + 1;
Random Color
Generate random hex colors
// Random hex color
"#" + Math.floor(Math.random()*16777215).toString(16);
Random Array Item
Pick random element from array
let arr = ["apple", "banana", "orange"];
arr[Math.floor(Math.random() * arr.length)];
Random Boolean
True or false randomly
// 50/50 chance
Math.random() < 0.5;
🔹 Random Integers
Generate random whole numbers in different ranges:
// Random integer from 0 to 9
let random0to9 = Math.floor(Math.random() * 10);
console.log("0-9:", random0to9);
// Random integer from 1 to 10
let random1to10 = Math.floor(Math.random() * 10) + 1;
console.log("1-10:", random1to10);
// Random integer from 5 to 15
let random5to15 = Math.floor(Math.random() * 11) + 5;
console.log("5-15:", random5to15);
// Generic function for any range
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log("Random 20-30:", randomInt(20, 30));
console.log("Random 100-200:", randomInt(100, 200));
// Test the function multiple times
for (let i = 0; i < 5; i++) {
console.log("Dice roll:", randomInt(1, 6));
}
Output (varies each time):
0-9: 7
1-10: 3
5-15: 12
Random 20-30: 27
Random 100-200: 156
Dice roll: 4
Dice roll: 1
Dice roll: 6
Dice roll: 2
Dice roll: 5
🔹 Random Decimals
Generate random decimal numbers in specific ranges:
// Random decimal from 0 to 1 (default)
console.log("0-1:", Math.random());
// Random decimal from 0 to 100
let random0to100 = Math.random() * 100;
console.log("0-100:", random0to100);
// Random decimal from 10 to 20
let random10to20 = Math.random() * 10 + 10;
console.log("10-20:", random10to20);
// Generic function for decimal range
function randomFloat(min, max, decimals = 2) {
let num = Math.random() * (max - min) + min;
return Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals);
}
console.log("Random 1.5-5.5:", randomFloat(1.5, 5.5));
console.log("Random price $10-$50:", "$" + randomFloat(10, 50, 2));
// Random percentage
function randomPercentage() {
return randomFloat(0, 100, 1) + "%";
}
console.log("Random percentage:", randomPercentage());
Output (varies each time):
0-1: 0.8234567891234567
0-100: 67.23456789123456
10-20: 15.789012345678901
Random 1.5-5.5: 3.47
Random price $10-$50: $32.85
Random percentage: 73.2%
🔹 Random Array Elements
Pick random items from arrays:
// Random array element
let fruits = ["apple", "banana", "orange", "grape", "kiwi"];
let randomFruit = fruits[Math.floor(Math.random() * fruits.length)];
console.log("Random fruit:", randomFruit);
// Generic function
function randomChoice(array) {
return array[Math.floor(Math.random() * array.length)];
}
let colors = ["red", "blue", "green", "yellow", "purple"];
console.log("Random color:", randomChoice(colors));
// Multiple random choices (with possible repeats)
function randomChoices(array, count) {
let choices = [];
for (let i = 0; i < count; i++) {
choices.push(randomChoice(array));
}
return choices;
}
console.log("3 random fruits:", randomChoices(fruits, 3));
// Random choice without repeats
function randomUniqueChoices(array, count) {
let shuffled = [...array].sort(() => 0.5 - Math.random());
return shuffled.slice(0, count);
}
console.log("3 unique fruits:", randomUniqueChoices(fruits, 3));
Output (varies each time):
Random fruit: banana
Random color: green
3 random fruits: ["apple", "grape", "apple"]
3 unique fruits: ["kiwi", "orange", "banana"]
🔹 Random Booleans and Probability
Create random true/false values and probability-based outcomes:
// Simple 50/50 random boolean
let coinFlip = Math.random() < 0.5;
console.log("Coin flip:", coinFlip ? "Heads" : "Tails");
// Custom probability (30% chance of true)
let thirtyPercent = Math.random() < 0.3;
console.log("30% chance:", thirtyPercent);
// Probability function
function randomChance(percentage) {
return Math.random() < (percentage / 100);
}
console.log("75% chance:", randomChance(75));
console.log("10% chance:", randomChance(10));
// Weighted random choice
function weightedChoice(choices, weights) {
let totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
let random = Math.random() * totalWeight;
for (let i = 0; i < choices.length; i++) {
random -= weights[i];
if (random <= 0) {
return choices[i];
}
}
}
let outcomes = ["common", "uncommon", "rare", "legendary"];
let probabilities = [50, 30, 15, 5]; // percentages
console.log("Loot drop:", weightedChoice(outcomes, probabilities));
Output (varies each time):
Coin flip: Heads
30% chance: false
75% chance: true
10% chance: false
Loot drop: common
🔹 Practical Random Examples
Real-world applications of random numbers:
// Random password generator
function generatePassword(length = 8) {
let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let password = "";
for (let i = 0; i < length; i++) {
password += chars[Math.floor(Math.random() * chars.length)];
}
return password;
}
console.log("Random password:", generatePassword(10));
// Random hex color
function randomHexColor() {
return "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
}
console.log("Random color:", randomHexColor());
// Shuffle array (Fisher-Yates algorithm)
function shuffleArray(array) {
let shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
let deck = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
console.log("Shuffled deck:", shuffleArray(deck));
// Random quote generator
let quotes = [
"The only way to do great work is to love what you do.",
"Innovation distinguishes between a leader and a follower.",
"Stay hungry, stay foolish.",
"Your time is limited, don't waste it living someone else's life."
];
function randomQuote() {
return randomChoice(quotes);
}
console.log("Random quote:", randomQuote());
Output (varies each time):
Random password: Kx9mP2nQ7s
Random color: #3a7bd4
Shuffled deck: ["7", "K", "2", "A", "9", "4", "J", "6", "10", "3", "Q", "8", "5"]
Random quote: Stay hungry, stay foolish.