Unit 4 · Thinking like a programmer
Why a countdown loop runs forever
A loop ends only when its condition becomes false. A countdown that keeps going while n >= 1 but steps with n++ moves away from the end, so it never stops. Count down with n--.
The mix-up
What people often think
“n++ and n-- do the same job.”
What the tutor says
n++ counts up from 5, so n stays above 1 forever and the loop never ends. A countdown needs n--.
How it works
Check that every pass moves the variable towards the exit. If the condition waits for n to drop, the step must make n smaller.
Also check where it stops. n >= 0 lets 0 through; n > 1 stops before 1. Fix the condition rather than adding an extra console.log after the loop to cover the gap.
Side by side
for (let n = 5; n >= 1; n++) {
console.log(n); // 5, 6, 7 ... forever
}for (let n = 5; n >= 1; n--) {
console.log(n); // 5, 4, 3, 2, 1
}Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Going down to 0 is close enough.”
n >= 0 lets 0 through as well. The loop should keep going while n is 1 or more: n >= 1.
“Adding console.log(1) after the loop is a fix.”
That hides the bug. The condition n > 1 stops the loop before 1, so change the condition.
Practise it with a tutor watching
Loops: doing it again
Trace a loop pass by pass, write one that counts, and fix one that stops a step early.
Free, no account needed.