Nested For Loops in JavaScript

Nested for loops in JavaScript means one for loop inside another for loop. In other words, a for loop placed inside another for loop is called nested for loops.

A nested for loops consists of an outer for loop and one or more inner for loops. Each time the outer for loop repeats, the control re-enters inside the inner for loop and starts a new execution.

That is, each time the control will enter inside the inner for loop when the outer for loop repeats. For example, we all know a date consists of hours, minutes, and seconds.

In a digital clock, the last branch of nested for loops is second counter. Above it there is minute counter. Above the minute counter, there is a hour counter. This is the best example of nested for loop.

We can put many loops inside a loop. But, it is advice that you do not go beyond three levels of nested loops, as it will make the program look clumsy.

Syntax of Nested For Loops in JavaScript


The general syntax for using nested for loops in JavaScript is as follows:

// Outer for loop.
 for ( initialization; test-condition; increment/decrement )
 {
// Inner for loop.
   for ( initialization; test-condition; increment/decrement )
   {
    // statement of inner loop
   }
 // statement of outer loop
 }

Let’s understand it with the help of an example.

for(var i = 1; i <= 3; i++)
{
  statement1; // This statement will execute 3 times when the value of i changes between 1 and 3.
}
for(var j = 1; j <= 4; j++)
{
  statement2; // This statement will execute 4 times when the value of j changes between 1 and 4.
}

If we write the second for loop inside the first for loop, it will look like this:

for(var i = 1; i <= 3; i++)
{
  statement1; // It will execute 3 times.
  for(var j = 1; j <= 4; j++)
  {
   statement2; // It will execute 12 (3 * 4) times.
  }
}

Explanation:

a) In this example, when i = 1, execution will start from the outer for loop and statement1 will execute once.

b) Now, the control of execution enters the inner for loop. Since the control variable j initially set to 1, statement2 will execute once.

c) After this execution, the value of j will be 2 because of increment by 1. Then, statement2 will execute once again.

d) Like this, the inner for loop will execute 4 times with changing j values from 1 to 4. This means that statement2 will execute 4 times in the first execution of the outer for loop.

e) As the execution of inner for loop completes, the control of execution goes to the outer for loop. Now, the value of i will be 2 because of increment by 1.

This time, the control again enters the inner for loop and statement2 will again execute 4 times.

f) Then, the control again goes to outer for loop and the value of i will be set to 3. Again, the inner for loop will execute 4 times.

This means that the values of i and j will change like this:

  • When i = 1, j = 1, 2, 3, 4
  • i = 2, j = 1, 2, 3, 4
  • i = 3, j = 1, 2, 3, 4

In the above sequence, the outer for loop will execute total 3 times, and hence statement1 inside the loop body will execute 3 times. But, the inner for loop will execute 4 times for each i value and hence statements2 inside the loop body will execute 12 times.


The general flowchart for nested loops in JavaScript has shown in the below figure.

Nested for loops in JavaScript

In the same way, we can also nest a while loop or a do-while loop inside a for loop and vice versa. These are called nested loops in JavaScript.

The general syntax to nest while loop inside a for loop is as:

for(initialization; test-condition; increment/decrement)
{
  statements;
  while(conditional expression)
  {
    statements;
  }
}

Example Program based on Nested For Loops


Let’s create a JavaScript program in which we will display values of the inner for loop for each outer iteration, as well as outer for loop.

Example 1:

<script>
// Outer for loop.
  for(var i = 1; i <= 3; i++)
  {
     document.write(i, "<br>"); // will execute 3 times.
  // Inner for loop.
     for(var j = 1; j <= 4; j++)
     {
       document.write(j, " "); // will execute 12 (3 * 4) times.
     }
     document.write("<br>");
  }
</script>
Output:
     1
     1 2 3 4
     2
     1 2 3 4
     3
     1 2 3 4

Printing Tables

Let’s create a JavaScript program to print tables using nested for loop.


Example 2:

<script>
  let i, j;
  document.write("Tables:", "<br>");
// Outer for loop.
  for(i = 1; i <= 2; i++)
  {
 // Inner for loop.
    for(j = 1; j <= 10; j++)
    {
      document.write(i+ " * " +j+" = "+ (i*j), "<br>");
    }
    document.write("");
  }
</script>
Output:
    Tables:
    1 * 1 = 1
    1 * 2 = 2
    1 * 3 = 3
    1 * 4 = 4
    1 * 5 = 5
    1 * 6 = 6
    1 * 7 = 7
    1 * 8 = 8
    1 * 9 = 9
    1 * 10 = 10
    
    2 * 1 = 2
    2 * 2 = 4
    2 * 3 = 6
    2 * 4 = 8
    2 * 5 = 10
    2 * 6 = 12
    2 * 7 = 14
    2 * 8 = 16
    2 * 9 = 18
    2 * 10 = 20

Displaying Triangle of *

Let’s write JavaScript program to display triangle of * using nested for loop.

Example 3:

<script>
   let i, j;
   document.write("Displaying a triangle of *:", "<br>");
// Outer for loop.
  for(i = 1; i <= 5; i++)
  {
  // Inner for loop.
     for(j = 1; j <= i; j++)
     {
       document.write("* ");
     }
     document.write("<br>");
   }
</script>
Output:
     Displaying a triangle of *:
     *
     * *
     * * *
     * * * *
     * * * * *

Displaying Triangle of Numbers

Let’s create a JavaScript program to display a triangle of numbers using nested for loops.

Example 4:

<script>
  let i, j;
  document.write("Displaying a triangle of numbers:", "<br>");
// Outer for loop.
  for(i = 1; i <= 5; i++)
  {
 // Inner for loop.
    for(j = 1; j <= i; j++)
    {
      document.write(j);
    }
    document.write("<br>");
  }
</script>
Output:
    Displaying a triangle of numbers:
    1
    12
    123
    1234
    12345

Displaying Right Triangle Pattern of Numbers

Let’s create a JavaScript program to display right triangle pattern of numbers.

Example 5:

<script>
   let i, j;
   document.write("Displaying Right Triangle Pattern:", "<br>");
// Outer for loop.
   let k = 1;
   for(i = 1; i <= 5; i++)
   {
  // Inner for loop.
     for(j = 1; j <= i; j++)
     {
       document.write(k);
     }
     document.write("<br>");
     k++;
   }
</script>
Output:
     Displaying right triangle pattern:
     1
     22
     333
     4444
     55555

Displaying Number Pattern

Let’s create a JavaScript program to display the following number pattern.

Example 6:

<script>
  let i, j;
  for(i = 5; i >= 1; i--)
  {
    for(j = 1; j <= i; j++)
    {
      document.write(j, " ");
    }
    document.write("<br>");
  }
</script>
Output:
      1 2 3 4 5
      1 2 3 4
      1 2 3
      1 2
      1

Displaying Alphabet Pattern

Let’s write JavaScript code to print the following alphabet pattern using JavaScript nested for loops.

Example 7:

<script>
  let i, j;
  for(i = 65; i <= 69; i++)
  {
    for(j = 65; j <= i; j++)
    {
      document.write(String.fromCharCode(j));
    }
    document.write("<br>");
  }
</script>
Output:
     A
     AB
     ABC
     ABCD
     ABCDE

Let’s create a JavaScript program to display another alphabet pattern using nested for loops.

Example 8:

<script>
  let i, j;
  for(i = 69; i >= 65; i--)
  {
    for(j = 65; j <= i; j++)
    {
      document.write(String.fromCharCode(j));
    }
    document.write("<br>");
  }
</script>
Output:
     ABCDE
     ABCD
     ABC
     AB
     A

More Example Patterns for Best Practice

Example 9:

<script>
  let i, j;
  let k = 65;
  for(i = 65; i <= 69; i += 2)
  {
     for(j = 69; j >= 65; j--)
     {
       if(j > i)
          document.write("&nbsp;&nbsp;");
       else
          document.write(String.fromCharCode(k++)+"&nbsp;&nbsp;");
     }
     document.write("<br>");
   }
</script>
Output:
      A  
    B  C  D  
  E  F  G  H  I 

Example 10:

<script>
  let i, j, k, m = 1;
  for(i = 1; i <= 5; i++)
  {
    for(j = 5; j > i; j--)
    {
      document.write("&nbsp;&nbsp;");
    }
    for(k = 1; k <= i; k++)
    {
      document.write(k +"&nbsp;&nbsp;");
    }
    document.write("<br>");
  }
</script>
Output:
     1  
    1  2  
   1  2  3  
  1  2  3  4  
 1  2  3  4  5  

Example 11:

<script>
  let i, j, k;
  for(i = 1; i <= 4; i++)
  {
     for(j = i; j < 4; j++)
     {
       document.write("&nbsp;&nbsp;");
     }
     for(k = 1; k < i*2; k++){
        document.write("*");
     }
     document.write("<br>");
  }
</script>
Output:
     *
    ***
   *****
  *******

In this tutorial, you learned nested for loops in JavaScript with various example programs. Hope that you will have understood the basic concepts of nested for loop and practiced design pattern programs. Stay tuned with the next tutorial where we will learn about break statement in JavaScript with important example programs.
Thanks for reading!!!