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.

Let’s see the working of nested for loop with an example.

Example 1

Here we will create a two-dimensional matrix of "#" using nested for loops.

Let’s look at the code for the same.

<!DOCTYPE html> <html> <body> <h3> The nested for loop in JavaScript</h3> <p> Enter number of rows and columns to create matrix</p> <form> <label >Rows : </label> <input type = "text" id = "rows"><br><br> <label > Columns : </label> <input type = "text" id = "cols"><br><br> <input type = "button" onclick = "fun()" value = "Create Matrix"> </form> <br><br> <div id="result"></div> <script> function fun(){ var text = ""; var rows = document.getElementById("rows").value; var cols = document.getElementById("cols").value; for(let i = 0 ; i < rows; i++){ for(let j = 0 ; j < cols ; j++){ text += "#" } text += "<br>"; } document.getElementById("result").innerHTML = text; } </script> </body> </html>

In the above code, we are taking inputs for the number of rows and columns and then using the nested loop for creating the specified matrix. Note that the terminating condition of the outer loop decides the number of rows in the matrix and that of the inner loop determines the number of columns.

The parameters (initialization value, terminating condition, updation) of the loop can be adjusted to use nested loops to realise almost any kind of nested traversal.

Let us see the use of nested loops to print a pyramid.

Example 2

Here we are going to create a pyramid using * symbol and the height provided by the user. Let’s look at the code for the same.

<!DOCTYPE html> <html> <body> <h3>The nested for loop in javascript</h3> <p>Enter the height of the pyramid:</p> <form> <label>Height : </label> <input type="text" id="height"><br><br> <input type="button" onclick="fun()" value="Create Pyramid"> </form> <br><br> <div id="result"></div> <script> function fun() { var text = ""; var height = document.getElementById("height").value; // loop 1 for (let i = 0; i < height; i++) { // loop 2 for (let j = 0; j < height - i; j++) { text += " " } // loop 3 for (let j = 0; j <= i; j++) { text += "*"; } text += "<br>"; } document.getElementById("result").innerHTML = text; } </script> </body> </html>

In the above code, as is visible in the output as well, upon changing the loop parameters, we can visualise many different traversal patterns.

Note that the outer loop (loop 1) in the program decides the height of the pyramid. The first inner loop (loop 2) decides the number of space characters in the start of every row. The second inner loop (loop 3) prints as many * characters as is the height of the pyramid in the current iteration.

Conclusion

Nested loops are a very useful construct that are very versatile and come to use on a regular basis.

Updated on: 10-Nov-2022

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements