Random Values JS Lesson
Learning about random values
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* 6
makes it bigger: 2.8962Math.floor()
chops off decimals: 2+ 1
shifts 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 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 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>