How to use nested for loop in JavaScript?

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the name suggests, is made up of more than one for loop one nested inside of the other. This allows us to loop over multidimensional data structures such as matrices.

The nested for loop in JavaScript

A simple for loop executes a specified number of times depending on the initialization value and the terminating condition. A nested for loop on the other hand, resides one or more for loop inside an outer for loop.

Syntax

for(let i = 0 ; i < limit; i++){
   // statement
}

This creates a simple for loop that executes limit number of times. This means that it executes the statements inside the loop body limit number of times.

In a nested loop the statement inside the for loop body is again a for loop. This causes The inside for loop to execute all the way through , for each iteration of the outer for loop.

for(let i = 0 ; i < limit; i++){
   for(let j = 0 ; j < limit; j++){
      // statement
   }
   // statement for outer loop
}

The inside loop in this example runs limit number of times for every iteration of the outer loop. So, in total, the loop runs limit x limit number of times.

The initialization value, terminating condition as well as updating of the loop variables for both loops are independent of one another.