Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

25 min

The for Loop

Trace initialization, condition and update

By the end of this lesson

  • Trace initialization, condition and update
  • Avoid off-by-one errors

Translate the repeated steps

A printer must produce three numbered collection slips: 1, 2 and 3. Predict how many times the body should run.

let printedCount = 0;
for (let slipNumber = 1; slipNumber <= 3; slipNumber = slipNumber + 1) {
  console.log(`Slip ${slipNumber}`);
  printedCount = printedCount + 1;
}
console.assert(printedCount === 3);

The initialization runs once. The condition is checked before each iteration. If true, the body runs, then the update runs. The next condition check decides whether to repeat. When the number becomes 4, the condition is false and the loop ends.

slipNumber++ is a shorter update equivalent here to adding one. We show the longer form first so the change is visible. The name declared with let inside the loop header belongs to that loop's scope.

Guided error analysis

Starting at 0 while keeping <= 3 prints four slips. Changing <= to < while starting at 1 prints only two. Trace the first and last permitted values instead of guessing the comparison sign.

Independent exercise

Calculate the sum of the whole numbers 1 through 5 with a loop. Predict the answer by hand, and then change the limit to 0. Explain why no iterations should run in the second case.

Correction

const limit = 5;
let sum = 0;
for (let value = 1; value <= limit; value++) {
  sum = sum + value;
}
console.assert(sum === 15);

With limit 0, the first comparison 1 <= 0 is false and sum remains 0. The algorithm assumes a nonnegative whole-number limit. Document that input assumption until validation is added.

Review

Write the initialization, condition, body and update in execution order. If a boundary change alters the number of iterations unexpectedly, reproduce it with a tiny limit rather than running a huge loop.

Lesson complete?

Your progress is saved on this device.