Loops
Learn how to repeat work automatically with JavaScript's for, while, for...of, and for...in loops — and when to reach for each one.
Imagine you need to send a "Happy Birthday" message to every person in a list of 500 friends. Writing that message 500 times by hand would be absurd — and if the list grows to 501, you'd have to write it again. Loops are JavaScript's answer to this: write a task once, and tell the computer to repeat it as many times as needed. Almost every real program uses loops, whether it's rendering a list of tweets, calculating a shopping cart total, or validating each item in an order.
#The Classic for Loop
for (let i = 0; i < 5; i++) {
console.log(`Step ${i}`);
}A for loop is like a treadmill timer
You set the start time (initialise), the end time (condition), and the interval (update). The treadmill runs each interval until the time is up — then it stops. The for loop works the same way: initialise once, check before each step, run the body, then update.
#The while Loop
let attempts = 0;
let correct = false;
while (!correct) {
attempts++;
if (attempts === 3) correct = true;
}
console.log(`Took ${attempts} attempt(s).`);Infinite loops will freeze your program
If the condition in a while loop never becomes false, the loop runs forever and the page (or Node process) hangs. Always make sure something inside the loop eventually makes the condition false — a counter that increments, a flag that flips, or user input that changes.
#for...of and for...in
// for...of — each VALUE from an array
const groceries = ["eggs", "milk", "bread"];
for (const item of groceries) {
console.log(`Buy: ${item}`);
}
// for...in — each KEY from an object
const scores = { Alice: 92, Bob: 78 };
for (const name in scores) {
console.log(`${name}: ${scores[name]}`);
}#forEach — Looping with a Callback
const colors = ["red", "green", "blue"];
colors.forEach((color, index) => {
console.log(`${index}: ${color}`);
});#break and continue — Controlling the Flow
const numbers = [3, 7, 2, 9, 4, 6, 1];
for (const n of numbers) {
if (n === 9) break; // stop the whole loop
if (n % 2 === 0) continue; // skip even numbers
console.log(n);
}Which loop is best for visiting every item in the array `["cat", "dog", "fish"]`?
Key takeaways
- Use `for` when you know the exact number of iterations or need a counter variable.
- `while` loops keep running until a condition becomes false — always ensure something inside will eventually stop it.
- `for...of` is the cleanest way to iterate over array values; `for...in` iterates over object keys.
- `forEach` is an array method that runs a callback per element and conveniently exposes the index alongside the value.
- `break` exits a loop immediately; `continue` skips the rest of the current iteration and moves on to the next.
What does this loop print to the console?
const numbers = [3, 7, 2, 9, 4, 6, 1];
for (const n of numbers) {
if (n === 9) break;
if (n % 2 === 0) continue;
console.log(n);
}This code has a bug — what's wrong?
let attempts = 0;
let correct = false;
while (!correct) {
if (attempts === 3) correct = true;
}
console.log(`Took ${attempts} attempt(s).`);Complete this classic for loop so it logs Step 0 through Step 4 (five steps total), matching the lesson's example.
for (let i = 0; i 5; i++) { console.log(`Step ${i}`); }
Arrange these lines into a working for...of loop that buys each grocery item, exactly as taught in the lesson.
console.log(`Buy: ${item}`);for (const item of groceries) {const groceries = ["eggs", "milk", "bread"];
}
You have an array of student grades. Write code that: (1) uses a for...of loop to print every grade, (2) uses continue to skip and only print passing grades (70 or above), and (3) uses a classic for loop to print each grade alongside its 1-based position number, like "1: 85".
Try it live — edit the code and hit Run to see the output: