Iterations JS Lesson
Learning about iterations
- 3.8 Iterations 🔄
- 🔥 Loop Types
- 1. For Loop - When you know how many times
- 2. While Loop - When you don't know how many times
- 3. Iterating through arrays
- 🚀 Array Methods (Modern & Cool!)
- 🎮 Loop Control
- 🔥 Loop Types
3.8 Iterations 🔄
Iteration = repeating code until a condition is met
🔥 Loop Types
1. For Loop - When you know how many times
// For loop structure: for (initialization; condition; increment/decrement)
for (let i = 3; i >= 1; i--) { // Start at 3, continue while i >= 1, decrease by 1 each time
console.log(i); // Prints: 3, 2, 1
}
console.log("🚀 BLAST OFF!"); // Prints after loop completes
2. While Loop - When you don't know how many times
let lives = 3; // Initialize counter variable
while (lives > 0) { // Loop continues as long as condition is true
console.log(`You have ${lives} lives left`); // Show current value
lives--; // Decrease lives by 1 (prevents infinite loop!)
}
console.log("💀 Game Over!"); // Prints when lives reaches 0
3. Iterating through arrays
const colors = ["red", "blue", "green"]; // Array with 3 elements at indices 0, 1, 2
for (let i = 0; i < colors.length; i++) { // Start at 0, go until length (3)
console.log(colors[i]); // Access each element using bracket notation
}
%%javascript
// 🚀 Try these basic loops - run this cell!
console.log("=== FOR LOOP ===");
// For loop structure: for (initialization; condition; increment/decrement)
// let i = 3: Creates a counter variable starting at 3
// i >= 1: Loop continues as long as i is greater than or equal to 1
// i--: Decreases i by 1 after each iteration
for (let i = 3; i >= 1; i--) {
console.log(i); // Prints current value of i
}
console.log("🚀 BLAST OFF!"); // Prints after loop completes
console.log("\n=== WHILE LOOP ===");
let lives = 3; // Initialize lives counter
// While loop: continues as long as the condition (lives > 0) is true
// IMPORTANT: Must update the condition variable inside the loop to avoid infinite loops!
while (lives > 0) {
console.log(`You have ${lives} lives left`); // Template literal to show current lives
lives--; // Decrement lives by 1 each iteration (prevents infinite loop)
}
console.log("💀 Game Over!"); // Prints when lives reaches 0
%%javascript
// 🎯 Two ways to iterate arrays
const fruits = ["🍎", "🍌", "🍊"]; // Array with 3 elements (indices 0, 1, 2)
// Method 1: Traditional for loop (when you need the index)
// i = 0: Start at index 0 (first element)
// i < fruits.length: Continue while i is less than array length (3)
// i++: Move to next index after each iteration
for (let i = 0; i < fruits.length; i++) {
console.log(`${i}: ${fruits[i]}`); // Access array element using bracket notation
// Prints: "0: 🍎", "1: 🍌", "2: 🍊"
}
// Method 2: for...of loop (cleaner when you don't need index)
// 'fruit' represents each element directly (no index needed)
// More readable and less error-prone than traditional for loop
// Use this when you just need the values, not their positions
for (const fruit of fruits) {
console.log(`I love ${fruit}!`); // 'fruit' is the actual value, not the index
// Prints: "I love 🍎!", "I love 🍌!", "I love 🍊!"
}
🚀 Array Methods (Modern & Cool!)
const numbers = [1, 2, 3, 4, 5];
// map = transform each element, returns NEW array
const doubled = numbers.map(n => n * 2);
// Result: [2, 4, 6, 8, 10]
// filter = keep only elements that pass the test
const evens = numbers.filter(n => n % 2 === 0);
// Result: [2, 4] (keeps only even numbers)
// find = return FIRST element that passes the test
const bigNumber = numbers.find(n => n > 3);
// Result: 4 (stops searching after first match)
🎮 Loop Control
// break = exit loop immediately
for (let i = 1; i <= 10; i++) {
if (i === 5) break; // Stops at 5
console.log(i); // Prints: 1, 2, 3, 4
}
// continue = skip to next iteration
for (let i = 1; i <= 5; i++) {
if (i === 3) continue; // Skips 3
console.log(i); // Prints: 1, 2, 4, 5
}
%%javascript
// 🎯 Find the first vowel in your name
const name = "YourName"; // Change this to your actual name!
// Loop through each character in the name string
for (let i = 0; i < name.length; i++) {
const letter = name[i].toLowerCase(); // Convert to lowercase for easier comparison
// .includes() checks if the string "aeiou" contains the current letter
// This is a shorthand way to check if letter is a vowel
if ("aeiou".includes(letter)) {
console.log(`First vowel: ${letter} at position ${i}`);
break; // BREAK: exits the loop immediately when first vowel is found
// Without break, it would find ALL vowels
}
}
// Note: If no vowel is found, nothing prints (could add message after loop)
%%javascript
// 🎯 Try it! Modify this countdown
// Standard countdown: 5, 4, 3, 2, 1
// i = 5: Start at 5
// i >= 1: Stop when i is less than 1
// i--: Subtract 1 each time (same as i = i - 1)
for (let i = 5; i >= 1; i--) {
console.log(i); // Prints: 5, 4, 3, 2, 1
}
console.log("🚀 Launch!");
// Challenge: Make it count by 2s from 10 to 0
// Hint: Change i = 5 to i = 10, and i-- to i -= 2 (subtract 2 each time)
// Expected output: 10, 8, 6, 4, 2, 0