What you'll learn
Loops turn one instruction into repeated work. You will choose the right loop, control it safely, and recognize the patterns behind counting, searching, and aggregation.
Counted repetition with for
A classic for loop places initialization, condition, and update in one header.
for (let count = 3; count >= 1; count -= 1) {
console.log(count);
}
console.log("Go!");Tip
index, row, or attempt communicates more than i outside tiny loops.while and do...while
Use while when you do not know the repetition count in advance. The condition is checked before every iteration. do...while checks afterward, so the body runs at least once.
let balance = 20;
let days = 0;
while (balance > 0) {
balance -= 6;
days += 1;
}
console.log(days, balance);Every while loop needs a path to stop
for...of vs for...in
| Loop | Iterates | Best for |
|---|---|---|
for...of | Values from an iterable | Arrays and strings |
for...in | Enumerable property keys | Object keys (with care) |
const topics = ["variables", "functions", "arrays"];
for (const topic of topics) {
console.log(topic);
}
const progress = { lessons: 6, quizzes: 5 };
for (const key in progress) {
console.log(key, progress[key]);
}Key idea
for...in for array values. It produces string keys and can include inherited enumerable properties.break and continue
break exits the nearest loop. continue skips the remaining body and starts the next iteration.
const values = [4, -2, 7, 12, 3];
for (const value of values) {
if (value < 0) continue;
if (value > 10) {
console.log(`Found: ${value}`);
break;
}
}Nested loops
for (let row = 1; row <= 3; row += 1) {
let line = "";
for (let column = 1; column <= 3; column += 1) {
line += `${row * column} `;
}
console.log(line.trim());
}If each loop handles n items, a nested pair may do n × n work. That matters later when collections grow.
Common iteration patterns
| Pattern | State you keep |
|---|---|
| Count | A number incremented for matches |
| Sum | An accumulator starting at zero |
| Search | Stop after the target is found |
| Transform | Build a new collection from each value |
const scores = [72, 88, 91, 64];
let total = 0;
let passes = 0;
for (const score of scores) {
total += score;
if (score >= 70) passes += 1;
}
console.log(`Average: ${total / scores.length}`);
console.log(`Passed: ${passes}`);Recap & quick check
Key takeaways
- Use for when the loop mechanics are count-based and while when repetition depends on state.
- for...of reads iterable values; for...in reads property keys.
- break exits and continue skips to the next iteration.
- Counting, summing, searching, and transforming are foundational loop patterns.
Quick check
1. Which loop runs its body at least once?
2. Which loop is clearest for array values?
3. What does continue do?
4. What should an accumulator for a sum usually start at?