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.
We'll begin by unveiling the format of a nested for
loop in TypeScript:
TypeScript1for (let i = 0; i < 3; i++) { 2 for (let j = 0; j < 3; j++) { 3 console.log(`i = ${i}, j = ${j}`); // e.g., "i = 0, j = 0" 4 } 5} 6/* 7Prints: 8i = 0, j = 0 9i = 0, j = 1 10i = 0, j = 2 11i = 1, j = 0 12i = 1, j = 1 13i = 1, j = 2 14i = 2, j = 0 15i = 2, j = 1 16i = 2, j = 2 17*/
For each progression of i
from 0
to 2
, we run through j
from 0
to 2
and display the respective values of i
and j
.
Just as with for
loops, while
loops can also be composed of nested loops:
TypeScript1let i = 0; 2while (i < 3) { 3 let j = 0; 4 while (j < 3) { 5 console.log(`i = ${i}, j = ${j}`); // e.g., "i = 0, j = 0" 6 j++; 7 } 8 i++; 9} 10/* 11Prints: 12i = 0, j = 0 13i = 0, j = 1 14i = 0, j = 2 15i = 1, j = 0 16i = 1, j = 1 17i = 1, j = 2 18i = 2, j = 0 19i = 2, j = 1 20i = 2, j = 2 21*/
In this case, too, the inner loop j
runs in its entirety for every single iteration of the outer loop i
.
To illustrate nested loops, let's observe a two-dimensional (2D) array — essentially an array of arrays:
TypeScript1let matrix: number[][] = [ 2 [1, 2, 3], 3 [4, 5, 6], 4 [7, 8, 9] 5]; 6 7for (let i = 0; i < matrix.length; i++) { // Iterating over each row. 8 let row = ''; 9 for (let j = 0; j < matrix[i].length; j++) { // Iterating over each element in the row. 10 row += `${matrix[i][j]} `; 11 } 12 console.log(row); 13} 14/* 15Prints: 161 2 3 174 5 6 187 8 9 19*/
For every i
row (outer loop), an inner loop goes through every element within that row.
Here is another example of a nested for
loop that creates a numerical pyramid:
TypeScript1for (let i = 1; i <= 5; i++) { // The first loop denotes each level of the pyramid. 2 let row = ''; 3 for (let j = 1; j <= i; j++) { // The second loop adds numbers to each level. 4 row += `${j} `; 5 } 6 console.log(row); // Prints each level of the pyramid. 7} 8 9/* 10Prints: 111 121 2 131 2 3 141 2 3 4 151 2 3 4 5 16*/
Congratulations! We've successfully discovered the workings of nested loops in TypeScript. We've investigated nested for
and while
loops, unearthed practical scenarios, and practiced with hands-on examples. Get ready for some practice assignments heading your way! Our challenge to you is to master nested loops. Are you up to the task? Go for it!