Phase 1 · FoundationsModule 6~35 min read

Loops & Iteration

Repeat work confidently with for, while, for...of, and safe loop-control patterns.

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.

countdown.js
for (let count = 3; count >= 1; count -= 1) {
  console.log(count);
}
console.log("Go!");

Tip

Use meaningful loop variables. 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.

while.js
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

If the condition can never become false, the loop blocks the main thread. Identify the changing value before you run it.

for...of vs for...in

LoopIteratesBest for
for...ofValues from an iterableArrays and strings
for...inEnumerable property keysObject keys (with care)
iteration.js
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

Do not use 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.

search.js
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

grid.js
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

PatternState you keep
CountA number incremented for matches
SumAn accumulator starting at zero
SearchStop after the target is found
TransformBuild a new collection from each value
aggregate.js
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?