Imagine you need to perform a task a specific, fixed number of times. This is where the 'for' loop shines. It's designed to repeat a block of code a predetermined number of iterations. Think of it like counting sheep: you know exactly how many sheep you want to count before you stop.
A 'for' loop typically has three main parts, often enclosed in parentheses after the for keyword:
- Initialization: This part runs only once at the very beginning of the loop. It's usually used to declare and initialize a loop counter variable. This variable keeps track of how many times the loop has run.
- Condition: This is a boolean expression that is checked before each iteration of the loop. If the condition is true, the loop continues. If it's false, the loop terminates.
- Increment/Decrement (or Update): This part runs after each iteration of the loop. It's typically used to update the loop counter, either by increasing it (incrementing) or decreasing it (decrementing), moving it closer to the termination condition.
for (let i = 0; i < 5; i++) {
console.log('This is iteration number: ' + i);
}Let's break down the code snippet above:
let i = 0;(Initialization): We declare a variableiand set its starting value to 0. Thisiis our loop counter.i < 5;(Condition): The loop will continue to run as long as the value ofiis less than 5.i++;(Increment): After each time the code inside the curly braces runs, the value ofiis increased by 1.
The output of this for loop will be:
This is iteration number: 0
This is iteration number: 1
This is iteration number: 2
This is iteration number: 3
This is iteration number: 4Notice that the loop runs 5 times, from i = 0 up to i = 4. When i becomes 5, the condition i < 5 is no longer true, and the loop stops.
graph TD;
A[Start]
B{Initialize counter i = 0}
C{Is i < 5?}
D[Execute loop body]
E{Increment i}
F[End]
A --> B
B --> C
C -- Yes --> D
D --> E
E --> C
C -- No --> F
The 'for' loop is incredibly useful for tasks like iterating through arrays, processing data sets of a known size, or simply repeating an action a specific number of times. It provides a concise and organized way to manage these repetitive actions.