Nested Loops

Basic Structure

Nested loops allow you to run a loop inside another loop. This is especially useful when working with multidimensional arrays, combinations of values, or matrix-style problems. Where conventionally you use i as a temporary variable in a loop, you would use j as a temporary variable for the nested loop.

for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 2; j++) {
        console.log(`i = ${i}, j = ${j}`);
    }
}
// This will print all combinations of i and j:
// i = 0, j = 0
// i = 0, j = 1
// i = 1, j = 0

Labelled Loops

Normally, break or continue only affects the current (innermost) loop. But using labels, you can direct break or continue to a specific loop, even if it is the outer loop. A label is an identifier followed by a colon (:) before a loop. You can use break labelName; or continue labelName; to control specific loops.

outerLoop:
for (let x = 0; x < 5; x++) {
    for (let y = 0; y < 5; y++) {
        if (y === 3) {
            console.log("Breaking outer loop from inner loop");
            break outerLoop; // Exits the outer loop
        }
        console.log(`x: ${x}, y: ${y}`);
    }
}