for Loop
Overview
The for loop repeats a block of code a specific number of times. It is the most traditional loop in programming and consists of three optional expressions enclosed in parentheses and separated by semicolons:
1. Initialization: Executed once before the loop starts (usually defining a counter). 2. Condition: Evaluated before every iteration. If true, the loop runs. If false, the loop terminates. 3. Final Expression: Executed at the very end of every iteration (usually incrementing the counter).
Syntax
// for (initialization; condition; final expression)
for (let i = 0; i < 5; i++) {
console.log("Iteration number: " + i);
}for (let i = 10; i > 0; i--) {
console.log(i + " seconds remaining...");
}Common Pitfalls
- Creating an infinite loop by messing up the condition or final expression (e.g.,
for (let i = 0; i >= 0; i++)). This will instantly crash the user's browser tab by exhausting all memory and CPU. - Using
varinstead ofletfor the counter.varis function-scoped, meaning the counter variable will leak out of the loop and be accessible in the rest of the code, leading to bizarre state bugs.
Interview Questions
var and let in a for loop's initialization?Variables declared with var are function-scoped, so the variable leaks outside the loop and has only one binding. Variables declared with let are block-scoped, so a new binding is created for each iteration. This is critical when putting async functions inside a loop.
Real-World Example
Generating an array of HTML strings for pagination page numbers.
const pages = [];
for (let i = 1; i <= totalPages; i++) {
pages.push(`<a href="?page=${i}">${i}</a>`);
}Check Your Knowledge
Test your understanding of for Loop with these quick questions.