Omitting Parts of a For Loop
You'll learn that for loop sections (initialization, condition, afterthought) are optional — you can leave them blank when they're not needed.
The Flexible For Loop Structure
You already know the standard for loop has three parts:
for (initialization; condition; afterthought) {
// loop body
}
Here's the secret: any or all of these parts can be omitted. The semicolons must stay, but the expressions are optional.
Omitting the Initialization
If you've already declared your counter variable, skip the initialization:
let i = 0; // already initialized
for (; i < 3; i++) {
console.log(i); // 0, 1, 2
}
Notice the semicolon stays — it marks where initialization would go.
Omitting the Afterthought
If you update your counter inside the loop body, you don't need the afterthought:
for (let i = 0; i < 5;) {
console.log(i);
i = i + 2; // manual increment inside
}
// Logs: 0, 2, 4
Omitting the Condition (Creates Infinite Loop)
Omitting the condition makes it always true:
for (let i = 0;; i++) {
if (i > 2) break; // must break manually
console.log(i);
}
// Logs: 0, 1, 2
Omitting Everything
You can create an infinite loop this way (though while (true) is clearer):
for (;;) {
console.log("Forever!");
break; // needed to escape
}
When Is This Useful?
Usually you'll omit parts when:
- Variables are initialized outside the loop
- Complex update logic belongs in the body
- You're converting a
whileloop pattern
Key Takeaway: All three parts of a for loop are optional — keep the semicolons but omit any section when initialization, condition, or update logic is handled elsewhere.