Understanding Nested Loops in JavaScript

This article is a complementary resource to the Learn JavaScript Basics course.

Understanding Nested Loops in JavaScript

In programming, loops allow us to repeat a block of code multiple times. But what if we need to handle multiple levels of repetition? This is where nested loops come in.

A nested loop is simply a loop inside another loop. This is useful when working with multi-dimensional structures, grids, patterns, and combinations of elements.

Before diving into practical examples like drawing shapes with loops, let’s first understand how nested loops work by looking at a simple example of combining two lists.


Example: Looping Through Two Lists

Imagine you have two lists: one containing car attributes and another containing car brands. If we want to print all possible combinations, we can use nested loops.


// List of car attributes
let attributes = ["Electric", "Fast"];

let cars = ["Tesla", "Porsche"];

for (let attribute of attributes) {
    for (let car of cars) {
        console.log(attribute, car);
    }
}

Output:

Electric Tesla
Electric Porsche
Fast Tesla
Fast Porsche
  • The outer loop iterates through the attributes array. It first picks "Electric", then "Fast".
  • For each iteration of the outer loop, the inner loop runs through all the items in the cars list.

Now that we understand the basics of nested loops, let's apply this concept to build different patterns using loops.


Example 1: Creating a Square Pattern

Imagine you want to draw a square using stars (*) like this:

* * *  
* * *  
* * *  

Step 1: Think About the Rows

  • A square has multiple rows. Since we want a 3×3 square, we need 3 rows.
  • Each row should contain 3 stars.

Step 2: Think About the Columns

  • Each row itself consists of multiple stars, printed side by side.
  • Since we need 3 stars per row, we need a loop that prints 3 stars in a row.

Step 3: Structure the Loops

  • The outer loop runs 3 times to create 3 rows.
  • The inner loop runs 3 times inside each outer loop iteration to print 3 stars per row.

for (let i = 0; i < 3; i++) {  
    let row = "";  
    for (let j = 0; j < 3; j++) {  
        row += "* ";  
    }
    console.log(row);  
}

Output:

* * *  
* * *  
* * *  

Key Takeaway:

  • Outer loop controls the number of rows.
  • Inner loop controls how many stars are printed per row.

Example 2: Right-Angled Triangle

Now, let’s say we want a triangle instead of a square:

*  
* *  
* * *  
* * * *  
* * * * *  

Step 1: Think About the Rows

  • A triangle grows with each row.
  • Row 1 → 1 star
  • Row 2 → 2 stars
  • Row 3 → 3 stars

Step 2: Think About the Inner Loop

  • The first row has 1 star → The loop runs 1 time.
  • The second row has 2 stars → The loop runs 2 times.
  • The third row has 3 stars → The loop runs 3 times.

Step 3: Code Implementation


let height = 5;
for (let i = 1; i <= height; i++) {  
    let row = "";
    for (let j = 0; j < i; j++) {  
        row += "* ";
    }
    console.log(row);
}

Output:

*  
* *  
* * *  
* * * *  
* * * * *  

Key Takeaway:

  • Outer loop controls the number of rows (5 rows).
  • Inner loop runs as many times as the row number (i).

Example 3: Inverted Triangle

Now, let's reverse the logic to make an inverted right-angled triangle:

* * * * *  
* * * *  
* * *  
* *  
*  

Step 1: Think About the Rows

  • The first row has the most stars, and each row after it has one less than the previous.

Step 2: Think About the Inner Loop

  • Instead of increasing, the inner loop should now decrease with each row.

Step 3: Code Implementation


let height = 5;
for (let i = height; i > 0; i--) {  
    let row = "";
    for (let j = 0; j < i; j++) {  
        row += "* ";
    }
    console.log(row);
}

Output:

* * * * *  
* * * *  
* * *  
* *  
*  

Takeaways – How to Think About Nested Loops

Step 1: Think About Rows (Outer Loop)

  • How many rows do I need?
  • Does the row count stay the same or change?

Step 2: Think About Columns or Elements (Inner Loop)

  • How many items do I need per row?
  • Does the number of items stay the same or change?

Step 3: Identify Any Conditions

  • Do I need special rules, like printing spaces inside a shape?
  • Do I need to change the loop behavior based on row number?

By following this step-by-step thinking process, you’ll be able to build any pattern using nested loops in JavaScript!