2.6 — for loops
Look at yesterday’s while loop: create a counter before, check it at the gate, change it inside. That trio is so universal that JavaScript gave it its own machine with three labeled slots: the for loop. Same engine as while — but the counter’s whole life story sits in one line, where nobody can forget the update and freeze the tab.
for (let i = 1; i <= 5; i = i + 1) {
console.log("Test run #" + i);
}
console.log("All done!");Read the header as three slots separated by semicolons: INIT (let i = 1), CHECK (i <= 5), UPDATE (i = i + 1). Three different jobs with three different schedules — watch when each one lights up.
The deeper story, with the real names for things — this part is what turns “I saw it” into “I can explain it.”
The formal execution order, worth having exactly right: init → check → body → update → check → body → … → check(false) → exit. Everything a for loop does, a while loop can do. for is purely a tidier arrangement: it keeps the counter’s birth, boundary and change in one line. That tidiness is real protection. The “forgot the update” infinite loop from 2.5 is nearly impossible in a for loop — the update slot stares at you from the header.
Two idioms to absorb now. Counting from zero — let i = 0; i < n — gives five laps, with i taking 0,1,2,3,4. It is the standard because it matches string and array positions. And i++ (“increment”) is the universal shorthand for i = i + 1 (i-- counts down).
💼 On the job — for loops drive data-driven tests: “for each of these 50 usernames, run the login test”. One body, fifty laps. And the counter tells you exactly which lap failed.
⌨️ countdown
A rocket launch: 3… 2… 1… Go! — where the counting is done by a loop, not by you.
requirements:
- The three numbers must be printed by a loop counting down — writing the digits 3, 2, 1 into print statements is not allowed.
Go!prints exactly once, after the counting is over.
when you press RUN, the console must show exactly:
✏️ Quick check 1
A loop you have NOT watched — different start, different step. Type the LAST number it prints:
for (let i = 2; i <= 8; i += 2) {
console.log(i);
}✏️ Quick check 2
In for (init; check; update) — which slot runs exactly once, no matter how many laps happen? Type its name.
✏️ Quick check 3
for (let i = 0; i < 5; i++) — the CHECK runs how many times in total? Type the number (careful — this is the off-by-one heart of loops).
🗣️ Now teach it back
Explain the for loop to a friend: what are the three slots, when does each run, and why do checks outnumber laps by exactly one?
Write it as if your friend is sitting next to you. Saved to your journal — future-you will use these notes to teach others.