JavaScript Mastery - Nested Loops

Code SubtleCode Subtle
7 min read

Easy Guide to Nested Loops in JavaScript

What are Nested Loops?

A nested loop is simply a loop inside another loop. Think of it like a clock - the hour hand (outer loop) moves once while the minute hand (inner loop) moves 60 times.

Basic Syntax

for (let i = 0; i < 3; i++) {        // Outer loop
    for (let j = 0; j < 2; j++) {    // Inner loop
        console.log(`i = ${i}, j = ${j}`);
    }
}

// Output:
// i = 0, j = 0
// i = 0, j = 1
// i = 1, j = 0
// i = 1, j = 1
// i = 2, j = 0
// i = 2, j = 1

Easy Examples

Example 1: Multiplication Table

// Print multiplication tables from 1 to 3
for (let table = 1; table <= 3; table++) {
    console.log(`Table of ${table}:`);
    for (let num = 1; num <= 5; num++) {
        console.log(`${table} x ${num} = ${table * num}`);
    }
    console.log('---');
}

Example 2: Simple Grid

// Create a 3x3 grid with coordinates
for (let row = 1; row <= 3; row++) {
    let line = '';
    for (let col = 1; col <= 3; col++) {
        line += `(${row},${col}) `;
    }
    console.log(line);
}

// Output:
// (1,1) (1,2) (1,3)
// (2,1) (2,2) (2,3)
// (3,1) (3,2) (3,3)

Example 3: Check All Combinations

// Find all pairs that add up to 5
let target = 5;
for (let a = 1; a <= 4; a++) {
    for (let b = 1; b <= 4; b++) {
        if (a + b === target) {
            console.log(`${a} + ${b} = ${target}`);
        }
    }
}

// Output:
// 1 + 4 = 5
// 2 + 3 = 5
// 3 + 2 = 5
// 4 + 1 = 5

Tips and Tricks

1. Use Different Variable Names

// Good - clear variable names
for (let row = 0; row < 3; row++) {
    for (let col = 0; col < 3; col++) {
        // Easy to understand
    }
}

2. Break Early When Possible

// Stop searching once found
let found = false;
for (let i = 0; i < 10 && !found; i++) {
    for (let j = 0; j < 10; j++) {
        if (i * j === 12) {
            console.log(`Found: ${i} x ${j} = 12`);
            found = true;
            break;
        }
    }
}

3. Watch Out for Performance

// Be careful with large numbers
for (let i = 0; i < 1000; i++) {        // 1000 iterations
    for (let j = 0; j < 1000; j++) {    // 1000 iterations each
        // This runs 1,000,000 times total!
    }
}

Pattern Printing with process.stdout.write()

What is process.stdout.write()?

process.stdout.write() prints text without adding a new line, unlike console.log(). Perfect for creating patterns!

// console.log() adds new line automatically
console.log("Hello");
console.log("World");
// Output:
// Hello
// World

// process.stdout.write() doesn't add new line
process.stdout.write("Hello");
process.stdout.write("World");
// Output: HelloWorld

// Add new line manually with \n
process.stdout.write("Hello");
process.stdout.write("\n");
process.stdout.write("World");
// Output:
// Hello
// World

Star Patterns

Pattern 1: Right Triangle

function rightTriangle(rows) {
    for (let i = 1; i <= rows; i++) {
        for (let j = 1; j <= i; j++) {
            process.stdout.write("* ");
        }
        process.stdout.write("\n");
    }
}

rightTriangle(5);
// Output:
// * 
// * * 
// * * * 
// * * * * 
// * * * * *

Pattern 2: Pyramid

function pyramid(rows) {
    for (let i = 1; i <= rows; i++) {
        // Print spaces
        for (let space = 1; space <= rows - i; space++) {
            process.stdout.write(" ");
        }
        // Print stars
        for (let star = 1; star <= 2 * i - 1; star++) {
            process.stdout.write("*");
        }
        process.stdout.write("\n");
    }
}

pyramid(5);
// Output:
//     *
//    ***
//   *****
//  *******
// *********

Pattern 3: Diamond

function diamond(rows) {
    // Upper half (including middle)
    for (let i = 1; i <= rows; i++) {
        for (let space = 1; space <= rows - i; space++) {
            process.stdout.write(" ");
        }
        for (let star = 1; star <= 2 * i - 1; star++) {
            process.stdout.write("*");
        }
        process.stdout.write("\n");
    }

    // Lower half
    for (let i = rows - 1; i >= 1; i--) {
        for (let space = 1; space <= rows - i; space++) {
            process.stdout.write(" ");
        }
        for (let star = 1; star <= 2 * i - 1; star++) {
            process.stdout.write("*");
        }
        process.stdout.write("\n");
    }
}

diamond(4);
// Output:
//    *
//   ***
//  *****
// *******
//  *****
//   ***
//    *

Number Patterns

Pattern 1: Number Triangle

function numberTriangle(rows) {
    for (let i = 1; i <= rows; i++) {
        for (let j = 1; j <= i; j++) {
            process.stdout.write(j + " ");
        }
        process.stdout.write("\n");
    }
}

numberTriangle(5);
// Output:
// 1 
// 1 2 
// 1 2 3 
// 1 2 3 4 
// 1 2 3 4 5

Pattern 2: Reverse Number Triangle

function reverseNumberTriangle(rows) {
    for (let i = rows; i >= 1; i--) {
        for (let j = 1; j <= i; j++) {
            process.stdout.write(j + " ");
        }
        process.stdout.write("\n");
    }
}

reverseNumberTriangle(5);
// Output:
// 1 2 3 4 5 
// 1 2 3 4 
// 1 2 3 
// 1 2 
// 1

Pattern 3: Number Pyramid

function numberPyramid(rows) {
    for (let i = 1; i <= rows; i++) {
        // Print spaces
        for (let space = 1; space <= rows - i; space++) {
            process.stdout.write(" ");
        }
        // Print numbers ascending
        for (let j = 1; j <= i; j++) {
            process.stdout.write(j.toString());
        }
        // Print numbers descending
        for (let j = i - 1; j >= 1; j--) {
            process.stdout.write(j.toString());
        }
        process.stdout.write("\n");
    }
}

numberPyramid(5);
// Output:
//     1
//    121
//   12321
//  1234321
// 123454321

Alphabet Patterns

Pattern 1: Alphabet Triangle

function alphabetTriangle(rows) {
    for (let i = 1; i <= rows; i++) {
        for (let j = 1; j <= i; j++) {
            let letter = String.fromCharCode(64 + j); // A=65, B=66, etc.
            process.stdout.write(letter + " ");
        }
        process.stdout.write("\n");
    }
}

alphabetTriangle(5);
// Output:
// A 
// A B 
// A B C 
// A B C D 
// A B C D E

Pattern 2: Alphabet Pyramid

function alphabetPyramid(rows) {
    for (let i = 1; i <= rows; i++) {
        // Print spaces
        for (let space = 1; space <= rows - i; space++) {
            process.stdout.write(" ");
        }
        // Print letters ascending
        for (let j = 1; j <= i; j++) {
            let letter = String.fromCharCode(64 + j);
            process.stdout.write(letter);
        }
        // Print letters descending
        for (let j = i - 1; j >= 1; j--) {
            let letter = String.fromCharCode(64 + j);
            process.stdout.write(letter);
        }
        process.stdout.write("\n");
    }
}

alphabetPyramid(5);
// Output:
//     A
//    ABA
//   ABCBA
//  ABCDCBA
// ABCDEDCBA

Pattern 3: Continuous Alphabet Triangle

function continuousAlphabetTriangle(rows) {
    let letterCode = 65; // Start with 'A'

    for (let i = 1; i <= rows; i++) {
        for (let j = 1; j <= i; j++) {
            let letter = String.fromCharCode(letterCode);
            process.stdout.write(letter + " ");
            letterCode++;
            if (letterCode > 90) letterCode = 65; // Reset to 'A' after 'Z'
        }
        process.stdout.write("\n");
    }
}

continuousAlphabetTriangle(5);
// Output:
// A 
// B C 
// D E F 
// G H I J 
// K L M N O

Quick Reference

Running Pattern Functions

// Test all patterns
console.log("=== Star Patterns ===");
rightTriangle(4);
console.log("\n");
pyramid(4);
console.log("\n");

console.log("=== Number Patterns ===");
numberTriangle(4);
console.log("\n");
numberPyramid(4);
console.log("\n");

console.log("=== Alphabet Patterns ===");
alphabetTriangle(4);
console.log("\n");
alphabetPyramid(4);

Key Points to Remember

  • Nested loops execute inner loop completely for each outer loop iteration

  • Use process.stdout.write() for patterns (no automatic new line)

  • Add \n manually for new lines

  • String.fromCharCode(65) gives you 'A', String.fromCharCode(66) gives you 'B', etc.

  • Always test with small numbers first to avoid infinite loops

  • Use meaningful variable names like row, col instead of i, j when possible

15
Subscribe to my newsletter

Read articles from Code Subtle directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Code Subtle
Code Subtle

At Code Subtle, we empower aspiring web developers through personalized mentorship and engaging learning resources. Our community bridges the gap between theory and practice, guiding students from basics to advanced concepts. We offer expert mentorship and write interactive, user-friendly articles on all aspects of web development. Join us to learn, grow, and build your future in tech!