JavaScript For Loop: Structure, Traversal & Nested Multi-Dimensional Loops

The for loop is the most versatile, compact, and ubiquitous loop construct in computer science. It encapsulates loop initialization, condition testing, and state incrementation into a single, clean header line.

Anatomy of the Classical For Loop

// for (initialization; condition; afterthought)
for (let i = 0; i < 5; i++) {
    console.log(`Current Index: ${i}`);
}

Common Traversal Patterns

1. Traversing an Array

const technologies = ["JavaScript", "Python", "PHP", "Linux"];

for (let i = 0; i < technologies.length; i++) {
    console.log(`Technology #${i + 1}: ${technologies[i]}`);
}

2. Reverse Traversal (Counting Backwards)

for (let i = 10; i >= 0; i -= 2) {
    console.log(`Countdown: ${i}`); // 10, 8, 6, 4, 2, 0
}

Nested For Loops (2D Grids & Patterns)

A loop inside another loop is known as a nested loop. The inner loop completes all its iterations for every single iteration of the outer loop:

// Generating a 3x3 Coordinate Matrix
for (let row = 1; row <= 3; row++) {
    let rowOutput = "";
    for (let col = 1; col <= 3; col++) {
        rowOutput += `[${row},${col}] `;
    }
    console.log(rowOutput);
}
// Output:
// [1,1] [1,2] [1,3]
// [2,1] [2,2] [2,3]
// [3,1] [3,2] [3,3]

University Exam Corner (BCA Examination Notes)

Classic Exam Problem: "Print a right-angled star pyramid pattern of height N using nested loops."

function printStarPyramid(height) {
    for (let i = 1; i <= height; i++) {
        let stars = "";
        for (let j = 1; j <= i; j++) {
            stars += "* ";
        }
        console.log(stars);
    }
}
printStarPyramid(4);
// * 
// * * 
// * * * 
// * * * * 

Next Step

What modern ES6 loops make iterating over objects and arrays 10x cleaner? Proceed to: JavaScript For..In vs For..Of Loops →

Explore Related JavaScript Tutorials

Accelerate your JavaScript mastery by studying these tightly connected core tutorials:

For..In & For..Of →

Iterating over object keys and array values.

Array Methods (map, filter) →

Modern functional iteration alternatives.

Break & Continue →

Managing loop control flow.

While Loop →

Indefinite vs definite iteration.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!