Course contentsShow
← JavaScript
Lesson 342 of 2,72310. LoopsFree lesson

The For Loop Structure

Master the three-part for loop syntax: initialization, condition, and afterthought.

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
}
  1. Initialization (let i = 0): Runs once before the loop starts. Creates your counter variable.
  2. Condition (i < 5): Checked before each iteration. If true, the loop body runs; if false, the loop stops.
  3. 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 → log 0
  • Afterthought: i++ (now i = 1)
  • Check: i < 3? Yes (1 < 3) → run body → log 1
  • Afterthought: i++ (now i = 2)
  • Check: i < 3? Yes (2 < 3) → run body → log 2
  • Afterthought: i++ (now i = 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.