Common For Loop Patterns
You'll learn the typical ways programmers use for loops: counting up, counting down, and stepping by different intervals.
The Core Idea
While the for loop structure is always the same, how you configure its three parts (initialization, condition, increment) creates different patterns. These patterns are like recipes—once you know them, you'll recognize them everywhere and write loops faster.
Counting Up (The Default Pattern)
The most common pattern counts from 0 upward:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
This prints five times, starting at zero. You'll use this constantly when working with lists of items.
Counting Down
Reverse the logic to count backward:
for (let i = 5; i > 0; i--) {
console.log(i); // 5, 4, 3, 2, 1
}
Notice the condition flips to > and the increment becomes a decrement (i--).
Stepping by Different Intervals
Instead of incrementing by 1, you can step by any amount:
// Count by twos
for (let i = 0; i < 10; i += 2) {
console.log(i); // 0, 2, 4, 6, 8
}
// Count by fives
for (let i = 0; i <= 50; i += 5) {
console.log(i); // 0, 5, 10, 15... 50
}
Think of this like skipping steps on a staircase—you're jumping multiple "steps" each iteration.
Starting from Any Number
You're not locked into starting at 0 or 1:
for (let i = 10; i < 15; i++) {
console.log(i); // 10, 11, 12, 13, 14
}
Key Insight
These patterns are just different combinations of where you start, which direction you go, and how big your steps are. Master these three, and you can loop through virtually any numeric sequence.
Key Takeaway: The three classic for loop patterns are counting up (i++), counting down (i--), and stepping by intervals (i += n)—they're all about controlling your starting point, direction, and step size.