Loading...

Nested for loops in JavaScript: Why?

Nested for loops in JavaScript: Why?

Hey readers, in this article we are going to discuss nested for loops in JavaScript. We will discuss How is the Nested for loop executed, Why do we use nested for loops, types of nested for loops, differences between a nested for loop and a for loop, etc. Let us get started without any delay.

Introduction

Loops in any programming language are used to implement certain instructions multiple times automatically. Why do you think is there a need for loops if we can manually give instructions? For less number of instructions, we can manage without using loops but to give a large set of the same instructions, loops become inevitable. You would have for sure heard about loops but what are these nested loops?

A loop within another loop is known as a nested loop. Generally, in loops, we will have only one statement that gets executed until the condition is satisfied. In the case of nested for loops, we will have conditions and statements of multiple loops. Shown below is what a nested for loop in JavaScript looks like.

for(var i=4;i<6;i++){     for(var j=4;j<5;j++){        console.log(i,j);     } }
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

4 4 5 4
Code language: Bash (bash)

Flowchart Of Nested For Loop

Below given is an image of the flowchart of how a nested for loop executes.

How is the Nested for loop executed?

Generally, in loops, we will have only one statement that gets executed when the condition is satisfied. What about a nested for loop? Let us understand with an example.

for(var i=4;i<6;i++){     for(var j=4;j<6;j++){        console.log(i,j);     } }
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

4 4 4 5 5 4 5 5
Code language: Bash (bash)

In the outer loop, the variable i is initialized to 4. As it is less than 6, which is the condition of the outer loop, the outer loop starts to execute. Now the variable j of the inner loop gets initialized to 4. As it is less than 6, which is the condition of the inner loop, the inner loop starts to execute. Now the value of i and j gets printed which are 4 and 4 respectively. Now the variable j of the inner loop gets incremented to 5. As it is less than 6 i.e satisfies the condition, the value of i and j gets printed which are 4 and 5 respectively. Now the value of j gets incremented to 6 which is not less than 6. So loop exits.

Now in the outer loop, the value of the variable i is incremented to 5. The value of i is less than 6, which is the condition, so the inner loop starts to execute. Like in the above case, the value of j, at the first iteration will be 4 and in the second iteration, it will be 5. So the output is 5,4 and 5,5.

Now the value of j gets incremented to 6 which is not less than 6. So the condition of the outer loop is not satisfied and the loop exits.

Why do we use nested for loop?

In the case of a 1-d array, we can iterate through its elements using a single for loop but what to do in the case of multidimensional arrays? We cannot use a single for loop for it. With the help of a nested for loop, we can iterate over the elements of the outer array as well as each element of the inner array. So we can perform operations accordingly. Let us understand how it is done with the help of an example.

var array1 = [[11,12,13], [14,15,16], [17,18,19]];  for (var i=0; i < array1.length; i++) {      for (var j=0; j < array1[i].length; j++) {          console.log(array1[i][j]);      }  }
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

11 12 13 14 15 16 17 18 19
Code language: Bash (bash)

We have printed the elements of a two-dimensional array using nested for loops. The outer loop is used to iterate over the elements of the outer array. The inner loop is used to iterate over the elements of the inner array. With their help, we are able to print all the elements. Similarly, we can use nested for loops for objects. In this case, the outer for loop will iterate over the outer array. The inner for loop will iterate over the properties of the object. So we can perform operations accordingly. They are useful where there is a need of iterating through multi-dimensional data structures such as tables, matrices, arrays, etc.

Types of nested for loops in JavaScript

For loop within another for loop

Example:

for(let i=0;i<3;i++){     for(let j=0;j<2;j++){        console.log(i,j);     } }
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

4 4 4 5 5 4 5 5 6 4 6 5
Code language: Bash (bash)

In the example given above, a for loop within another for loop. The outer loop has a variable i whereas the inner loop has a variable j. The variable i goes from 0 to 2 whereas j goes from 0 to 1. So for each iteration of the outer loop, the total inner loop gets executed.

For loop inside a for…in loop

let obj={"one":1, "two":2} for(let key in obj){   for(let i=1;i<3;i++){     console.log(key,i);   } }
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

one 1 one 2 two 1 two 2
Code language: Bash (bash)

The example given above is of a for loop inside a for…in loop. The outer loop iterates over the elements of the object. The variable of the inner loop iterates from 1 to 2 with an increment of 1. So for each iteration of the outer loop, the total inner loop gets executed. In this example, the inner loop iterates four times.

For loop inside a for…of loop

let array1=["a", "b"] for(let j of array1){   for(let i=1;i<3;i++){     console.log(j,i);   } }
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

a 1 a 2 b 1 b 2
Code language: Bash (bash)

The example given above is of a for loop inside a for…of loop. For each iteration of the outer loop, the total inner loop gets executed. In this example, the inner loop iterates four times.

JavaScript loop statements

There are multiple loop statements in JavaScript that allows user to implement certain instructions multiple times automatically. Let us discuss some of them.

For loop

We can use for loop to execute certain lines of the code number of times. The syntax of for loop contains three parameters. In the first parameter, we should initialize the loop variable to a certain value. The second parameter contains the condition. For every iteration of the loop, the condition gets checked. The third parameter contains an increment or decrement of the value of the loop variable. Let us understand it with the help of an example.

Example:

for(let i=10;i<13;i++){ console.log(i) }
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

10 11 12
Code language: Bash (bash)

While loop

We can use a while loop to execute certain lines of the code number of times. It has only one parameter which is the condition. For every iteration of the loop, the condition gets checked. While the condition is true, the loop executes and gives the output according to the code. If the condition turns out to be false, then the loop exits. We should specify the initial value of the loop variable outside the loop unlike the for loop. Let us understand it with the help of an example.

let j=10; while (j<12){ console.log(j); j++; }
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

10 11
Code language: Bash (bash)

do…while loop

We can use a while loop to execute certain lines of the code number of times. It has only one parameter which is the condition. For every iteration of the loop, the condition gets checked. While the condition is true, the loop executes and gives the output according to the code. It is similar to that of a while loop but there is only one difference. In a while loop, if none of the values of the loop variable satisfies the condition, the loop doesn’t execute at all. In the case of a do…while loop, even when none of the values of the loop variable satisfies the condition, at least the loop gets executed once. Let us understand it with the help of an example.

let k=10; do{ console.log(k); k++; } while(k<12);
Code language: JavaScript (javascript)

The above example is also available in a codedamn playground for you to modify and run.

The output for the above example is as shown below.

10 11
Code language: Bash (bash)

Differences between ‘nested for loops’ and ‘for loop’

For loopNested for loop
Syntax:
for(initialization, condition, increment){
    code
}
Syntax:
for(initialization, condition, increment){
    for(initialization, condition, increment){
        and so on….
    }
}
A single for loop is usedMultiple loop statements can be used
It consists of a single loopIt can consist of multiple loops
It consists of only a single loop variableIt can consist of multiple loop variables
A single set of code is executed continuously until the condition returns falseFor each iteration of the outer loop, the total inner loop gets executed.

Conclusion 

In this article, we have discussed nested for loops in JavaScript, how is the nested for loop executed, why we use nested for loops,  types of nested for loops, and differences between a nested for loop and a for loop. It is the end of this article. Do check out this JavaScript course at codedamn to continue your learning. There are a lot of projects available at codedamn from which you can choose and start working on it as projects play an important role.

Frequently Asked Questions- FAQ

What is a nested for loop?

A loop within another loop is known as a nested loop.

What is the Importance of nested loops in javascript?

They are useful where there is a need of iterating through multi-dimensional data structures such as tables, matrices, arrays, etc.

What is the syntax of for loop?

Syntax:

for(initialization, condition, increment){     statement }

What is the main advantage of nested for loops in JavaScript?

With the help of a nested for loop, we can directly access the elements of an array, unlike other nested loops.

What is the difference between a while loop and a do…while loop?

In a while loop, if none of the values of the loop variable satisfies the condition, the loop doesn’t execute at all. In the case of a do…while loop, even when none of the values of the loop variable satisfies the condition, at least the loop gets executed once.

Sharing is caring

Did you like what Manish wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: