Skip to main content

Loops: Repeating Work

beginner14 min readLesson 31 of 143

for and while β€” make the computer do the boring thousand times, and defuse the classic off-by-one trap.

Computers shine at repetition. A loop runs the same block again with small changes each pass.

The for loop

for (let i = 1; i <= 5; i++) {
  console.log("Visitor number " + i);
}

Three parts, separated by semicolons:

  1. Start: let i = 1 β€” runs once, before anything else
  2. Condition: i <= 5 β€” checked before every pass; loop stops when false
  3. Step: i++ β€” runs after every pass (adds 1)

So this logs 1, 2, 3, 4, 5 β€” five passes.

Counting from 0 β€” the classic trap

Arrays (next lesson) start at index 0, so most loops look like:

for (let i = 0; i < 5; i++) {
  // 0,1,2,3,4 β€” exactly 5 passes
  console.log(i);
}

Note the condition: i < 5, not i <= 5. Starting at 0 with < gives exactly 5 passes; mixing up the two is the most common beginner loop bug. Check yours against this rule every time.

while β€” loop until something changes

let cups = 3;

while (cups > 0) {
  console.log("Cups left: " + cups);
  cups = cups - 1; // something must change, or the loop never ends!
}

while is best when you do not know how many passes you need. If the condition never becomes false you get an infinite loop β€” the tab freezes.

Looping with a purpose: accumulating

let total = 0;
for (let n = 1; n <= 10; n++) {
  total = total + n; // add each number into the running total
}
console.log(total); // 55

The pattern β€” declare an accumulator before the loop, update it inside β€” powers sums, counting, building strings, and most data processing you will do this module.

What you learned

  • for: start; condition; step
  • Count from 0 with i < n; from 1 through n with i <= n
  • while repeats until its condition goes false β€” always change something inside
  • Accumulator pattern: declare before, update inside

Next: bundling code into reusable functions.

Now practice

Loops: Repeating Work β€” PracticeHands-on practice for β€œLoops: Repeating Work”: apply what you just learned in js-loops.2 challenges Β· Β· ~10 min