Loops and iteration
Repeat work with for, for...of and while, and know when an array method is better.
- Write for, for...of and while loops
- Use break and continue to control a loop
- Decide when an array method is clearer than a loop
In plain English
A loop is a block of code that runs repeatedly while a condition is true. A for loop runs a fixed number of times with a counter, and a while loop keeps running until a condition turns false. A for...of loop visits each item of an array one by one, which is the cleanest way to read every value. The break keyword exits a loop early and continue skips to the next round; when you only need to read or change an array, methods like map, filter and forEach do the looping for you and are often easier to read.
Step by step
- 1Use for...of to add up the numbers in an array.
- 2Write a while loop that counts down to zero.
- 3Add a break so the loop stops early when a condition is met.
- 4Replace a simple loop with map, filter or forEach and compare readability.
const scores = [12, 45, 33, 50, 41];
let total = 0;
for (const score of scores) {
total = total + score;
}
console.log("Total:", total);
let countdown = 3;
while (countdown > 0) {
console.log(countdown);
countdown = countdown - 1;
}
const passed = scores.filter((score) => score >= 40);
console.log("Passed:", passed);Common mistakes
- Creating an infinite loop by forgetting to change the counter or condition inside a while loop.
- Using a classic for loop with an index when for...of would be clearer.
- Confusing break (stop the whole loop) with continue (skip one round).
- Modifying an array while you loop over it, which causes confusing results.
First passing score
Write a function firstPassing(scores) that returns the first score that is 40 or more. Return null if none pass.
function firstPassing(scores) {
}Which statement skips the current round and moves to the next one?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.