Nested Loops JavaScript


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.

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.

Related post

Iterating Through 2D Array Java

Java, , , , ,

We explored using for loops with one-dimensional arrays. Now let’s jump into nested for loops as a method for iterating through 2D arrays. A nested for loop is one for loop inside another. Take a look below to see what this means. package exlcode; public class Iteration2DExample { public static int[][] exampleVariableOne = {{0, …

Read more
Python Dictionary with For Loop

Python, ,

Using the dictionary structure with for loops is incredibly efficient in python. In this card, I will show you some examples of ways to use dictionaries in for loops. The first example I am going to cover is expanding a dictionary into a list of lists. Lets imagine that you have a dictionary where the …

Read more