for Loop: Iteration, Counters, & NestingThe for loop executes a block of code repeatedly until a specified condition evaluates to false. It consists of three optional expressions: initialization, condition check, and final increment/decrement expression.
for Loop Execution Lifecycleflowchart TD
Init["1. Initialization (let i = 0)"] --> Condition{"2. Condition Check (i < max)?"}
Condition -- "True" --> Body["3. Execute Loop Body Block"]
Body --> Inc["4. Increment / Update (i++)"] --> Condition
Condition -- "False" --> Exit["5. Exit Loop"]
for Loop Structure Anatomy// for (initialization; condition; increment)
for (let i = 0; i < 5; i++) {
// Loop body statement
}
// Demonstrating standard for loops, reverse iteration, and matrix processing
// 1. Standard Forward Loop
console.log("--- Forward Loop ---");
for (let i = 1; i <= 3; i++) {
console.log(`Count: ${i}`);
}
// 2. Reverse Loop (Counting down)
console.log("
--- Countdown Loop ---");
for (let i = 3; i > 0; i--) {
console.log(`Countdown: ${i}`);
}
// 3. Nested Loop (Matrix / Grid Processing)
console.log("
--- 2D Matrix Iteration ---");
const grid = [
[1, 2],
[3, 4]
];
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
console.log(`Grid[${row}][${col}] = ${grid[row][col]}`);
}
}
// 4. Multiple Counters in Single Loop
for (let i = 0, j = 10; i < 3; i++, j -= 2) {
console.log(`i=${i}, j=${j}`);
}
let: Always declare loop counters with let (for (let i = 0; ...)) so each iteration receives a block-scoped binding.for (let i = 0, len = arr.length; i < len; i++).false and the increment updates the counter correctly.Write a for loop that prints all even numbers from 0 to 20 in steps of 2 (i += 2).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.