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: 4