Loops: Repeat Work and Track State

Add each subject without copying the instruction

A teacher needs a total for three marks today and five marks tomorrow. Writing one addition statement per subject repeats the same rule and becomes awkward when the list changes.

A loop repeats a body of instructions. Each repetition is an iteration. A collection loop processes its items; a condition-based loop repeats while its condition permits it.

  1. Trace state

    Follow the running total after each mark.

  2. Choose a loop

    Compare collection iteration with counter-controlled repetition.

  3. Handle boundaries

    Explain empty-list behavior and why updates must make progress.

Accumulate three marks

  1. First mark

    Add 40 to the initial total zero.

    total → 40
  2. Second mark

    Read the current total and add 35.

    total → 75
  3. Third mark

    Add 25, then finish the list.

    total → 100
Read these stages alongside the complete example. They explain the relationship; they do not execute code.

A running total needs a deliberate starting value

Initialize total to zero before processing marks. Each iteration reads one mark and adds it to the current total. Placing the initialization inside the body would erase the previous work.

JavaScript for...of reads values from an iterable such as an array. A conventional for loop explicitly controls a counter. A while loop tests a condition before each iteration. These forms can express similar work, but choose the one that shows your intent most clearly.

Before starting, review updates using current values. These examples use JavaScript; other languages can use different syntax and rules.

Read the list and build the total

for...of assigns each array value to mark in turn. The output shows intermediate totals 40, 75 and 100, making the accumulating state visible.

After the list is exhausted, the final output prints 100 again. The loop does not know these are exam marks; it simply follows the addition rule.

JavaScript · local teaching example

const marks = [40, 35, 25];
let total = 0;
for (const mark of marks) {
  total += mark;
  console.log(total);
}
console.log(total);

Expected output

40
75
100
100

A counter loop has a start, a test and an update

The for header initializes index to zero, checks index < marks.length before each body, and increments index after the body. Bracket indexing retrieves the selected mark.

With three entries, valid indices are 0, 1 and 2. Using <= would also reach index 3, where there is no mark.

JavaScript · local teaching example

const marks = [40, 35, 25];
for (let index = 0; index < marks.length; index++) {
  console.log(marks[index]);
}

Expected output

40
35
25

A while condition is tested before the body

This while loop prints three student numbers. The update moves the counter toward the false condition. Once studentNumber becomes four, the next test fails.

A do...while loop instead executes its body before testing, so it runs at least once. Choose it only if that first execution is intended.

JavaScript · local teaching example

let studentNumber = 1;
while (studentNumber <= 3) {
  console.log(studentNumber);
  studentNumber += 1;
}

Expected output

1
2
3

Apply the rule to a small change

Use the same total rule on an empty marks array. What should be printed after the loop?

Worked answer

There are no iterations, so the initialized total remains zero. Whether a report should display zero or “No marks entered” is a separate school requirement; an average would need a nonzero count check.

JavaScript · local teaching example

const marks = [];
let total = 0;
for (const mark of marks) {
  total += mark;
}
console.log(total);

Expected output

0

Recognize mistakes and limits

Do not reset accumulated state inside each iteration unless the task requires that reset. Verify whether a loop processes values or indices; JavaScript for...in lists property keys rather than array values.

Loops need a finite collection or a route to a false condition. Nested loops can multiply work: processing every pair in a class of n students can require about n squared comparisons. Do not add nested repetition without a reason.

For the language or tool rules used here, see JavaScript iteration rules.

Check the core idea

JavaScript · code for this question

const marks = [40, 35, 25];
let total = 0;
for (const mark of marks) {
  total += mark;
  console.log(total);
}
console.log(total);
Why is total initialized outside the loop?
Choose one answer. You can try again.

Answer and explanation

To preserve earlier additions across iterations.

Yes. Each later mark adds to the existing running total.

Apply the idea to a new situation

For three marks, which counter condition selects only valid indices?
Choose one answer. You can try again.

Answer and explanation

index < marks.length

Yes. Starting at zero selects indices 0, 1 and 2.

Trace the state after every iteration

A loop repeats work while a list or condition permits it. Initialize shared state before the loop, update it deliberately, and test empty inputs and exact boundaries.

Connect this idea with stopping or skipping iterations and termination conditions.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Break, Continue and Pass: Control Repetition →