Exploring Nested Loops in TypeScript

Introduction

Our path today leads through the realm of Exploring Nested Loops in TypeScript. Think of these as revolving mechanisms within each other, much like solar systems within galaxies, each having its own distinct motion. We'll delve deep and learn how to efficiently manipulate these loops in TypeScript by the end of this tutorial.

Structure of a Nested for Loop in TypeScript

Structure of a Nested while Loop in TypeScript

Iterations and Nested Loops: An Example

To illustrate nested loops, let's observe a two-dimensional (2D) array — essentially an array of arrays:

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

for (let i = 0; i < matrix.length; i++) {   // Iterating over each row.
    let row = '';
    for (let j = 0; j < matrix[i].length; j++) {  // Iterating over each element in the row.
        row += `${matrix[i][j]} `; 
    }
    console.log(row);
}
/*
Prints:
1 2 3
4 5 6
7 8 9
*/

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

Iterations and Nested Loops: Another Example

Here is another example of a nested for loop that creates a numerical pyramid:

for (let i = 1; i <= 5; i++) { // The first loop denotes each level of the pyramid.
    let row = '';
    for (let j = 1; j <= i; j++) { // The second loop adds numbers to each level.
        row += `${j} `;
    }
    console.log(row); // Prints each level of the pyramid.
}

/*
Prints:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/
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