Skip to content

for & while Loops

The Course
•
20 min study

A loop repeats a block. A for loop has a starting step, a condition checked before each pass, and an update after each pass. In for (let day = 1; day <= 3; day = day + 1), the block runs for 1, 2, and 3. At 4 the condition is false.

An accumulator holds a result across passes. Initialize it before the loop. Putting let total = 0 inside would erase the previous work each time. total += 20 is a shorter way to write total = total + 20; learn the long form first so you know what it means.

A while loop checks a condition before each repetition too, but you write the update in its body. Every loop needs a way to finish. If you accidentally remove the update and it keeps running, use the editor's Stop control. Do not test deliberately endless loops.

Predict before running

Write a small table with columns day and total. What is total after the second pass? Change the target from three days to four.

Predict, then run JavaScript
let total = 0;

for (let day = 1; day <= 3; day = day + 1) {
  total = total + 20;
}

console.log(total);
Check your prediction
Text
60

Trace each statement in order. If your prediction differed, describe the first place your mental model and the result diverged before trying again.

Trace a changing total

A trace table is a debugging tool you can make on paper. Record the counter and total after each pass. This makes it easier to distinguish a wrong update from a wrong stopping condition.

Passdaytotal after adding day
111
223
336

The update day = day + 1 runs after the body. The condition runs again before the next body. Once day is 4, the body is skipped and execution continues after the loop.

Trace a changing total JavaScript
let total = 0;

for (let day = 1; day <= 3; day = day + 1) {
  total = total + day;
  console.log(`${day}: ${total}`);
}

console.log(`Final: ${total}`);
Check your prediction
Text
1: 1
2: 3
3: 6
Final: 6

The trace is observable evidence for the table. Changing the condition to day < 3 drops the third pass.

Choose the loop from the question

Use a counting for loop when the number of steps is known. Use while when a condition describes unfinished work. Neither choice removes your responsibility to update the state correctly. Increasing a counter while checking whether it stays above zero can move away from termination.

Fix on paper first: a countdown starts at 3, checks remaining > 0, and adds one each time. Replace the update before running so it moves toward zero. Then decide whether zero should be printed: that requirement changes where you place the print and what comparison you use.

A useful habit is to test zero iterations, one iteration, and several iterations. Starting with an already-satisfied goal should not accidentally add one more session.

Reading a while loop

The shape is while (condition) { instructions }: check the condition, run the instructions if it is true, then check again. Unlike the three-part for-loop header, there is no automatic update slot. Put the update inside the body. In your exercise, total < 40 is the question and adding 10 moves total toward the stopping point.

Trace the test, body and update separately

A for loop does not run all three parts on every line. Initialization happens once; the condition is checked before each body; the update happens after a completed iteration. When the condition is false initially, the body never runs. This is why an accumulator needs a useful value before entering the loop.

A while loop uses the same repeated test, but you place the update in its body. Write a reason the condition will eventually become false before running it. Avoid experimenting with an unbounded loop just to see what happens: the useful skill is predicting termination.

The last allowed value JavaScript
let total = 0;

for (let day = 1; day <= 3; day = day + 1) {
  console.log(day);
  total = total + 10;
}

console.log(total);
Check your prediction
Text
1
2
3
30

The <= comparison includes day 3. After its body, the update makes day 4, and the next check stops the loop. Replacing <= with < changes both the number of iterations and the total.

A loop can do no work JavaScript
let savings = 60;
let days = 0;

while (savings < 50) {
  savings = savings + 15;
  days = days + 1;
}

console.log(days);
console.log(savings);
Check your prediction
Text
0
60

The goal is already met before the first test. The correct answer is zero new saving days. Initializing days to one would bake an iteration into the result even though none happened.

Try the rule on new inputs

For the saving loop, try starting amounts 0, 49 and 50. Record the condition before each iteration and the amount afterward. Then translate the bounded for example into a while loop with the same outputs.

Debug a plausible mistake

Exercise

Repair the accumulator

Total the amounts 10, 20 and 30 and print 60. Keep the loop and derive each amount from day. Test an empty traversal and one day after repair.

Predict the supplied program's actual behavior first. It runs without an error, but breaks the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.

Debugging workspace JavaScript
let total = 0;

for (let day = 1; day <= 3; day++) {
  total = day * 10;
}

console.log(total);
Hint 1: the idea

Traversal can be correct while its update loses earlier work.

Hint 2: a first step

Use the previous total in the assignment, with the accumulator initialized outside the loop.

Show one solution
JavaScript
let total = 0;

for (let day = 1; day <= 3; day++) {
  total += day * 10;
}

console.log(total);
Text
60

The original printed 30. total = day * 10 replaced the total on every pass, so only the last day survived. total += day * 10 adds each amount to what is already there: 10, then 30, then 60. Because total starts at 0 outside the loop, a loop that runs zero times prints 0, and one day prints 10.

Before you move on

In a loop that counts 1 to 3, the body runs three times, then the counter becomes 4 and the test fails. Create the total before the loop, add to it inside the body, and print it after. A total created inside the body starts again from zero every time.

Your turn

Exercise

for & while Loops: practice

Use a while loop to add 10 minutes at a time until total reaches 40. Print 10, 20, 30, and 40 on separate lines. Check that it stops.

Your working space JavaScript
let total = 0;
// Repeat while total is below 40.
Hint 1: the idea

The condition should describe unfinished work, not finished work.

Hint 2: a first step

Inside while (total < 40), increase total before printing it.

Show one solution
JavaScript
let total = 0;

while (total < 40) {
  total = total + 10;
  console.log(total);
}
Text
10
20
30
40

The loop ends because total changes toward the boundary. If the starting total were already 40, the body would run zero times.

What you should be able to explain

  • Describe initialization, condition, body, and update in their actual execution order.
  • What happens if the condition is false before the first pass?
  • Make a trace table for adding 10 until a total reaches 30.

Was this article helpful?

Your response is saved on this device.