Introduction and Topic Actualization

Hello, learner! Today's journey is into the cosmos of JavaScript's nested loops. Imagine nested loops as loops inside loops, much like galaxies with star systems rotating on their axes while also revolving around their galaxy center. Intriguing, isn't it? By the end of this session, you'll understand how to use nested loops in JavaScript and control them effectively.

Structure of a Nested 'for' Loop in JavaScript

Let's decipher the structure of a nested for loop in JavaScript:

for (let i = 0; i < 3; i++) {
   for (let j = 0; j < 3; j++) {
       console.log('i =', i, ', j =', j); // e.g., "i = 0 , j = 0"
    }
}
/*
Prints:
i = 0 , j = 0
i = 0 , j = 1
i = 0 , j = 2
i = 1 , j = 0
i = 1 , j = 1
i = 1 , j = 2
i = 2 , j = 0
i = 2 , j = 1
i = 2 , j = 2
*/

For every value of i from 0 to 2, we traverse j from 0 to 2 and print the current pair of i and j.

Structure of a Nested 'while' Loop in JavaScript

Much like for loops, while loops can also be nested:

let i = 0;
while (i < 3) {
    let j = 0;
    while (j < 3) {
        console.log('i =', i, ', j =', j); // e.g., "i = 0 , j = 0"
        j++;
    }
    i++;
}
/*
Prints:
i = 0 , j = 0
i = 0 , j = 1
i = 0 , j = 2
i = 1 , j = 0
i = 1 , j = 1
i = 1 , j = 2
i = 2 , j = 0
i = 2 , j = 1
i = 2 , j = 2
*/

Here again, the inner loop j runs in full for every individual iteration of the outer loop i.

Nested Loops in JavaScript: Real-life Example

Let's dive into some examples of nested loops. Consider the task of iterating over a two-dimensional (2D) array, which is an array of arrays:

let matrix = [
    [1, 2, 3],
    [4, 5, 6], 
    [7, 8, 9]
];

for (let i = 0; i < matrix.length; i++) {   // Going through each row.
    let row = '';
    for (let j = 0; j < matrix[i].length; j++) {  // Going through each element in the row.
        row += matrix[i][j] + ' '; // implicit conversion of matrix[i][j] to string
    }
    console.log(row);
}
/*
Prints:
1 2 3
4 5 6
7 8 9
*/

For every row i (outer loop), an inner loop parses every element within that row.

Nested Loops in JavaScript: Another Example
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal