Why We Need Loops
Loops let you repeat a block of code multiple times. Without them, you'd have to write the same code over and over for repetitive tasks. JavaScript has several loop types — choose based on what you're iterating over.
The for Loop
The classic loop. Three parts: initialization, condition, update. Best when you know how many times to loop.
// Basic for loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`); // 0, 1, 2, 3, 4
}
// Counting backward
for (let i = 10; i >= 0; i--) {
console.log(i); // 10, 9, 8... 0
}
// Stepping by 2
for (let i = 0; i <= 20; i += 2) {
console.log(i); // 0, 2, 4... 20
}
// Looping through an array by index
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i}: ${fruits[i]}`);
}
// for...of — cleaner for arrays (ES6)
for (const fruit of fruits) {
console.log(fruit); // apple, banana, cherry
}
// for...in — for object properties
const person = { name: "Alice", age: 30, city: "NYC" };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
while and do-while
// while — runs while condition is true
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// Real use case: wait for user input or condition
let attempts = 0;
let success = false;
while (!success && attempts < 3) {
attempts++;
// simulate trying something
success = Math.random() > 0.5;
console.log(`Attempt ${attempts}: ${success ? 'success' : 'fail'}`);
}
// do-while — executes at least once, THEN checks condition
let input;
do {
input = prompt("Enter a number greater than 0:");
} while (Number(input) <= 0);
// Runs at least once regardless of condition
// Infinite loop guard — always ensure the loop WILL terminate:
// DANGEROUS:
// while(true) { } // runs forever!
// SAFE infinite loop with break:
let i = 0;
while (true) {
if (i >= 10) break;
console.log(i++);
}
Array Iteration Methods (Better than for loops)
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// forEach — execute code for each element
numbers.forEach((num, index) => {
console.log(`${index}: ${num}`);
});
// map — transform each element, returns new array
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
// filter — keep elements that pass a test
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6, 8, 10]
// find — first element that passes a test
const firstBig = numbers.find(n => n > 7);
// 8
// some — does any element pass?
const hasNegative = numbers.some(n => n < 0); // false
// every — do all elements pass?
const allPositive = numbers.every(n => n > 0); // true
// reduce — collapse to single value
const sum = numbers.reduce((acc, n) => acc + n, 0); // 55
// Chain methods together!
const result = numbers
.filter(n => n % 2 === 0) // [2,4,6,8,10]
.map(n => n ** 2) // [4,16,36,64,100]
.reduce((sum, n) => sum + n, 0); // 220
⚡ Key Takeaways
- Use
for...ofto iterate over arrays — cleaner than index-based for loops - Use
for...infor object properties whileis best when you don't know the iteration countdo-whilealways executes at least once- Array methods (
map,filter,reduce) are more expressive than manual loops - Always ensure a loop has a termination condition — infinite loops freeze the browser
🎯 Practice Exercises
EXERCISE 1
Use a for loop to print a multiplication table for numbers 1-10 (10x10 grid).
EXERCISE 2
Given an array of products with prices, use array methods to: (1) filter products under $50, (2) apply a 10% discount to each, (3) calculate the total price of discounted products.
EXERCISE 3 — CHALLENGE
Implement a function that finds all prime numbers up to n using the Sieve of Eratosthenes algorithm.