Loops & Iteration: Mastering Repetition

Loops & Iteration: Mastering Repetition

Iteration is the engine of computing. It allows a single block of code to process thousands of data points, automate repetitive tasks, and manage complex data structures like arrays and objects. In JavaScript, choosing the right loop is not just about syntax—it's about performance, readability, and avoiding the dreaded "infinite loop."

This chapter covers the full spectrum of iteration, from classic counting loops to modern, declarative patterns.


Why This Topic Matters

Loops are everywhere. Mastering them will help you:

  • Process Large Data Sets: Transform, filter, or aggregate information from APIs.
  • Automate Logic: Perform the same action (like sending an email or updating a UI) for every user in a list.
  • Build Complex Structures: Generate grids, game boards, or nested menus.
  • Optimize Performance: Understand which loops are fastest for specific tasks and how to exit them early to save resources.

The Anatomy of a Loop

Every loop needs three components to function correctly. If any are missing or incorrect, the loop may never run, or worse, never stop.

1. StartInitialization2. CheckCondition3. UpdateIncrement


The Classic for Loop

The for loop is the most versatile. It gives you total control over exactly how many times the code should run.

// for (Initialization; Condition; Update)
for (let i = 0; i < 5; i++) {
  console.log(`Iteration: ${i}`);
}
  • Initialization: let i = 0 — Runs once before the loop starts.
  • Condition: i < 5 — Checked before every iteration. If false, the loop stops.
  • Update: i++ — Runs after every iteration.

while and do...while

The while Loop

Use this when you don't know exactly how many times you need to loop, but you know the condition that should stop it.

let power = 1;
while (power < 100) {
  power *= 2;
  console.log(power);
}

The do...while Loop

Identical to while, but it always runs at least once, because the condition is checked at the end.

let score = 0;
do {
  console.log("Welcome to the game!");
  score++;
} while (score < 0); // Condition is false, but code ran once anyway.

Modern Iteration: for...of and for...in

for...of (Values)

The cleanest way to iterate over Arrays, Strings, and Sets. It gives you the actual value directly.

const fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
  console.log(fruit);
}

for...in (Keys)

Used to iterate over the properties (keys) of an Object.

const car = { make: "Tesla", model: "Model 3", year: 2023 };
for (const key in car) {
  console.log(`${key}: ${car[key]}`);
}

Warning: Avoid using for...in for Arrays, as it iterates over indices (as strings) and may include inherited properties.


Controlling the Flow: break and continue

Sometimes you need to interrupt the normal cycle of a loop.

  • break: Exits the loop entirely.
  • continue: Skips the rest of the current iteration and jumps to the next one.
for (let i = 1; i <= 10; i++) {
  if (i === 3) continue; // Skip 3
  if (i === 7) break;    // Stop at 7
  console.log(i);        // Prints: 1, 2, 4, 5, 6
}

Nested Loops & Grids

Loops inside loops are common for processing 2D data like tables or images.

Row 2, Col 1

for (let row = 1; row <= 3; row++) {
  for (let col = 1; col <= 3; col++) {
    console.log(`Cell: ${row}-${col}`);
  }
}

Common Mistakes

  1. Infinite Loops: Forgetting to update the counter (i++), causing the browser to freeze.
  2. Off-by-One Errors: Using i <= array.length instead of i < array.length.
  3. Using for...in for Arrays: Getting strings instead of numbers for indices, and potentially hitting prototype methods.
  4. Inefficient Nesting: Placing heavy calculations or database calls inside a nested loop (O(n²) complexity).

Mini Exercises

  1. The Countdown: Write a for loop that counts down from 10 to 1 and then logs "Blast off!".
  2. Even Hunter: Write a loop that logs only the even numbers between 1 and 20.
  3. Object Explorer: Create an object representing a movie. Use for...in to log all its properties and values.
  4. The Summation: Use a while loop to calculate the sum of numbers from 1 to 100.
  5. Nested Stars: Use nested loops to log a 5x5 grid of * characters to the console.

Review Questions

  1. What are the three parts of a standard for loop header?
  2. How does a do...while loop differ from a standard while loop?
  3. When is for...of better than a traditional for loop?
  4. What happens if you forget a break in a loop that is supposed to exit early?
  5. Why is it dangerous to use for...in on an Array?

Reference Checklist

  • I can write a standard for loop from memory.
  • I understand how to avoid infinite loops.
  • I can use for...of to iterate over an array.
  • I know the difference between break and continue.
  • I can iterate over object properties using for...in.
  • I understand how nested loops work for 2D data.