Coding Rooms transition to “read-only” state on August 31, 2024  Click here for more information.

Nested Loops JavaScript

Learn how to use nested loops in JavaScript

October 6, 2020
by
Sasha Varlamov

A composition of loops is called a nested loop. The most common type of nested loops will be one loop inside another. The first loop is usually called the outer loop while the second loop is called the inner loop. The outer loop always executes first, and the inner loop executes inside the outer loop each time the outer loop executes once. Take a look at the example below and visualize how the nested loop works.

for (counter = 1; counter < 4; counter++) { 
    // count from 1 to 3 three times
    console.log("Count from 1 to 3");
    for (counterTwo = 1; counterTwo < 4; counterTwo++){
        console.log(counterTwo);
    }
}

The sample code above runs the outer loop and the inner loop four times each. The program prints the numbers 1-3 4 different times. The inner loop prints the individual digits while the outer loop determines how many times this task is repeated. Try changing counter < 4 to counter < 1. The numbers 1 through 3 should only be printed once if this change is made. This is because the outer loop is only executed once. If the break; statement existed in the inner loop, it will only exit the inner loop, not the outer loop.

Sasha Varlamov
Sasha Varlamov

Coding Rooms
Founder and CEO

October 6, 2020

Learn why these organizations choose Coding Rooms as their next-generation learning platform.