The For Loop Structure
You'll learn: How to write a for loop using its three-part syntax: initialization, condition, and afterthought.
The Compact Powerhouse
The for loop packages three critical pieces into one compact line, making it the go-to choice when you know exactly how many times you want to repeat something. Think of it like a recipe instruction: "Stir 10 times" — you need a starting point (first stir), a stopping rule (until you hit 10), and a way to count each stir.
The Three Parts
for (initialization; condition; afterthought) {
// code to repeat
}
- Initialization (
let i = 0): Runs once before the loop starts. Creates your counter variable. - Condition (
i < 5): Checked before each iteration. If true, the loop body runs; if false, the loop stops. - Afterthought (
i++): Runs after each iteration. Typically updates your counter.
Seeing It in Action
for (let i = 0; i < 3; i++) {
console.log(i);
}
// Output:
// 0
// 1
// 2
Execution flow:
- Initialize:
i = 0 - Check:
i < 3? Yes (0 < 3) → run body → log0 - Afterthought:
i++(nowi = 1) - Check:
i < 3? Yes (1 < 3) → run body → log1 - Afterthought:
i++(nowi = 2) - Check:
i < 3? Yes (2 < 3) → run body → log2 - Afterthought:
i++(nowi = 3) - Check:
i < 3? No (3 is not < 3) → stop
Key Takeaway: The for loop's three-part structure (initialization; condition; afterthought) compactly controls repeated execution, making it ideal when you need a counter-based loop.