Random Values JS Lesson
Learning about random values
- 🎲 3.15 Random Values
- 🔥 The Magic Formula
- Random number from 1 to 6 (like a dice)
- 🎮 Random Choice from a List
- 🎯 50/50 Chance (Coin Flip)
- 🎁 Challenge: Loot Box!
- 🔥 The Magic Formula
🎲 3.15 Random Values
Random Values = unpredictable numbers (like rolling dice!)
🔥 The Magic Formula
Random number from 1 to 6 (like a dice)
Math.floor(Math.random() * 6) + 1
How it works:
Math.random()gives a decimal like 0.4827* 6makes it bigger: 2.8962Math.floor()chops off decimals: 2+ 1shifts it up: 3 ✅
Want different numbers? Change the 6!
Math.floor(Math.random() * 10) + 1→ 1 to 10Math.floor(Math.random() * 100) + 1→ 1 to 100
%%javascript
// 🎲 Roll a dice! Run this cell multiple times!
const diceRoll = Math.floor(Math.random() * 6) + 1;
console.log(`You rolled: ${diceRoll}`);
%%javascript
// 🎯 Try it yourself! Change the numbers
// Random number 1-10
const random10 = Math.floor(Math.random() * 10) + 1;
console.log(`Random 1-10: ${random10}`);
// Random number 1-100
const random100 = Math.floor(Math.random() * 100) + 1;
console.log(`Random 1-100: ${random100}`);
🎮 Random Choice from a List
Pick one random item from an array:
const colors = ["red", "blue", "green"];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
The trick: colors.length tells you how many items (3),
so you get 0, 1, or 2!
%%js
// 🎨 Pick a random color!
const colors = ["🔴 Red", "🔵 Blue", "🟢 Green", "🟡 Yellow"];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
console.log(`You got: ${randomColor}`);
// Run multiple times to see different colors!
🎯 50/50 Chance (Coin Flip)
if (Math.random() < 0.5) {
console.log("Heads"); // 50% chance
} else {
console.log("Tails"); // 50% chance
}
Why 0.5? Math.random() gives values from 0 to 0.999...,
so half the time it’s less than 0.5!
%%js
// 🪙 Flip a coin!
if (Math.random() < 0.5) {
console.log("🪙 Heads!");
} else {
console.log("🪙 Tails!");
}
// Run it 10 times - you'll get about 5 heads and 5 tails!
🎁 Challenge: Loot Box!
Use Math.random() to make a simple game where you have different chances:
- 70% chance = Common
- 25% chance = Rare
- 5% chance = Legendary
%%javascript
// 🎁 Open a loot box!
const chance = Math.random(); // Get random number 0 to 0.999...
if (chance < 0.70) {
console.log("⚪ Common Item"); // 0 to 0.70 = 70%
} else if (chance < 0.95) {
console.log("🔵 Rare Item"); // 0.70 to 0.95 = 25%
} else {
console.log("🟡 Legendary!"); // 0.95 to 1 = 5%
}
// Run this many times - legendary is rare!
<IPython.core.display.Javascript object>