Start learning free

LESSON 250 OF 675 · NESTED LOOPS

Nested loops in TypeScript

Lesson

A nested loop has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below. When a loop is nested inside another loop, the inner loop runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.

Example:

for(let row = 0; row < 3; row++) {
	for(let col = 0; col < 5; col++) {
		process.stdout.write("*");
	}
    process.stdout.write('\n');
}

// This code prints a rectangle with 3 rows and 5 columns, filled with '*'
// We use process.stdout.write because console.log prints with a trailing newline

Iterating through multidimensional arrays

Nested loops are also helpful when we want to iterate through a multi dimensional array, for example:

const arr = [
	[1, 2], [3, 4], [5, 6]
];

for (let i = 0; i < arr.length; i++) {
	for (let j = 0; j < arr[i].length; j++) {
		console.log(arr[i][j]);
	}
}

This outputs each sub-element in arr one at a time. Note that for the inner loop, we are checking the .length of arr[i], since arr[i] is itself an array.

Breaking nested loops

In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. For example:

const arr = [
	[1, 2], [3, 4], [5, 6]
];

for (let i = 0; i < arr.length; i++) {
	for (let j = 0; j < arr[i].length; j++) {
		if(arr[i][j] == 3) {
			break;
		}
		console.log(arr[i][j]);
	}
}

// prints the numbers 1, 2, 5 and 6 on different lines

When i is 1 and j is 0, we execute the break. This means we stop the inner loop and go back to the outer loop to continue from the next iteration, which is i = 2. And as you can see, we print all the elements of row 2.

However, if the break is placed in the outer loop, all of the looping stops. For example:

const arr = [
	[1, 2], [3, 4], [5, 6]
];

for (let i = 0; i < arr.length; i++) {
	if(arr[i][0] == 3) {
		break;
	}
	for (let j = 0; j < arr[i].length; j++) {
		console.log(arr[i][j]);
	}
}
// prints the numbers 1 and 2 on different lines


Assignment
Follow the Coding Tutorial and let's write some nested loops.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check