37. Introduction to Looping
Loops are fundamental to programming. They allow you to execute a block of code repeatedly until a specific condition is met. This avoids writing repetitive code (following the DRY—Don't Repeat Yourself—principle).
Core Components of a Loop
Most traditional loops require three parts:
- Initialization: Setting up a counter variable (e.g.,
let i = 0). - Condition: The test that determines if the loop continues (e.g.,
i < 10). If the condition is false, the loop stops. - Iteration/Update: Modifying the counter variable so that the loop eventually terminates (e.g.,
i++).
The for Loop (The Workhorse)
The for loop is the most common type and combines all three components into a concise structure.
javascript for (let i = 0; i < 5; i++) { console.log('Iteration number: ' + i); }
// Output: 0, 1, 2, 3, 4
We will now look at for, while, and do...while in detail.