25 min·beginner

Lesson 7

Loops & iteration

Build a practical mental model for loops & iteration and use it in working JavaScript.

By the end, you will be able to…

  • Explain loops & iteration in your own words
  • Use loops & iteration in a small program
  • Recognize and debug a common failure mode

Build the mental model

Loops repeat work a controlled number of times. A for loop tracks its own counter explicitly, while for...of iterates values directly — pick whichever makes the intent clearest.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: lap 0 lap 1 lap 2

Why this matters

Almost every list-processing task — rendering rows, totaling a cart, validating entries — starts as a loop before it's refactored into array methods.

Real-world example

A pagination system looping over pages of results to prefetch data uses exactly this counter-controlled pattern.

Common mistakes

  • Off-by-one errors from using <= instead of < (or vice versa)
  • Forgetting to increment the counter, causing an infinite loop
  • Reaching for a manual loop when array.map/filter/reduce would be clearer

Try it yourself

Challenge

Fix the off-by-one bug so the loop prints exactly 5 numbers, 1 through 5.

Practice

Knowledge check

What almost always causes an infinite loop?

Summary

Use for loops when you need explicit index control, and for...of or array methods otherwise.