Nested Loops

The code inside a for loop can be any code that can run outside of the loop, which means you can use one loop inside another loop.

Here is an example to illustrate the concept (pay attention to indention and the brackets):

for (let i = 0; i < 3; i++) {
    for (let j = 7; j <9; j++) {
        console.log(i, j);

Note: use different counter variable names (i and j) in nested loops.

Console results:

0 7
0 8
1 7
1 8
2 7
2 8

JavaScript coding style:

Indentation: indent each for loop body by 4 spaces relative to the for loop header line.

Brackets: each for loop has it's own set of brackets: the opening bracket at the end of the loop header line; the closing bracket on a new line, line up with the corresponding for key word.

results matching ""

    No results matching ""