For Loop in JavaScript | Example Program

The for loop in JavaScript is an entry-controlled loop structure that executes a block of statements a certain number of times.

The for statement provides a more concise syntax for creating loops. It executes a block of code as long as the condition is true.

The structure of for loop comprises three parts, separated by semicolon: initialization, test condition, and increment or decrement.

The general syntax for using for loop in JavaScript is as follows:

for(initialization; test-condition; increment/decrement) // This line determines how many times loop will repeat. 
{
 // Loop body
   statement(s);
 }
Or,
for (i = initialValue; i < endValue; i++) 
{
 // Loop body
  statement(s);
}

In the above syntax, for loop statement begins with a keyword for, followed by a pair of parentheses enclosing the loop control structure.

This loop control structure comprises three parts:

  • Initialization,
  • Test condition,
  • Increment or decrement (Iteration)

The body of loop enclosed inside curly braces follows this control structure. Semicolon (;) separates the initialization, test condition, and iteration. There is no semicolon at the end iteration section.

How does for loop works in JavaScript?


JavaScript for loop works like this:

1. Initialization of control variables: A for loop uses a variable to control how many times the body of loop will execute and when the body of loop ends.

This variable is called control variable. We assign it using an assignment operator, such as i = 1 or count = 0. It sets up the initial state for the loop.

JavaScript interpreter performs only once it when a for statement executes. The variables i and count are called loop control variables.

2. Test condition: The test condition is a boolean expression, such as i < 10 that determines when the loop will stop running.

JavaScript interpreter evaluates the boolean expression before each loop iteration (execution). When the condition is true, the loop body executes.

When the condition is false, the loop ended, and the execution continues to the next statement after closing a curly brace that immediately follows the loop.

3. Iteration: When the loop body executes, the control of execution transfers back to the for statement after executing the last statement in the loop.

The assignment statements such as i++ (i.e. i = i + 1), or i– (i.e. i = i -1) increments or decrements the control variable. The new value of control variable again evaluates to see whether it satisfies the loop condition.

If the test condition satisfies, the loop body again executes. This process continues as long as the value of control variable does not satisfy to test condition.

The flowchart of the for loop statement in JavaScript has shown in the below figure (a).

JavaScript For loop example flowchart diagram

A simple example of For Loop

Consider the following example code.

for(var i = 1; i <= 5; i++ )
{
  document.write("Hello JavaScript");
}

Let’s understand how for loop is working in this example. The flowchart of statement has shown in the above figure (b).

The first expression (var i = 1) creates a variable named i and assigns it an initial value of 1. Expression i = 1 sets up the initial state for the loop and will execute only once for the first time.

The test condition (I <= 5) is a boolean expression. The expression (i <= 5) will test right after the initialization and at the beginning of each iteration. If this condition is true, the statement inside the loop body will execute and prints “Hello JavaScript”.

The increment expression (i++) will execute again. As a result, the value i becomes 2. Since the value of i is less than 5, therefore, the statement will execute and prints “Hello JavaScript” again.

This process continues until the value of i is greater than 5. If it is greater than 5, the expression (i <= 5) will be false and the loop ends.

Thus, we understood from the above discussion, the expression (i = 1) will execute only once at the starting of the loop. Then, expressions (i <= 5) and (i++) will execute repeatedly until i is less than or equal to 5.

If there is only one statement in the body of loop, as in this example, we can omit the curly braces.

Example Program based on for loop statement


1. Let’s consider an example program where we will display numbers from 1 to 5 and from 5 to 1 using for loop statement.

Program code 1:

<script>
  document.write("Displaying numbers from 1 to 5:", "<br>");
  for(var i = 1; i <= 5; i++) { // Here, i++ is increment operator.
     document.write(i, "<br>");
  }
  document.write("Displaying numbers from 5 to 1:", "<br>");
  for(var j = 5; j > 0; j--) { // Here, j-- is decrement operator.
     document.write(j, "<br>");
  }
</script>
Output:
   Displaying numbers from 1 to 5:
   1
   2
   3
   4
   5
   Displaying numbers from 5 to 1:
   5
   4
   3
   2
   1

We can also write the same for loop like this:

let i = 1;
for(; i <= 5;) {
   document.write(i, "<br>");
   i++;
}

2. Let’s consider another program in which we will calculate the sum of squares of integer numbers from 1 to 5 using for loop statement. Look at the following script code to understand better.

Program code 2:

<script>
  let i = 1;
  let sum = 0;
  for(; i <= 5;)
  {
    sum = sum + i*i;
    i++;
  }
 document.write("Sum = " +sum);
</script>
Output:
    Sum = 55

3. Let us consider a program in which we will initialize two variables inside for statement and will display numbers from 1 to 5 and 5 to 1 simultaneously.

Program code 3:

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

In this for loop structure, we have used two initialization expressions (i = 1, and j = 5) and two iteration expressions (i++, and j- -). But, there is only one test conditional expression (i < = 5). The loop will print i and j values from 1 to 5 and from 5 to 1, respectively.


Note: The for loop can have more than one initialization expression and iteration expression. This feature cannot apply in other loops. Each expression must separate from the next by comma.


Program code 4:

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

In this example, the initialization section comprises two control variables x and y that comma has separated. The expressions (x++ and y- -) separated by commas in the iteration section will execute each time the loop repeats.

Try It Yourself

Program code 5:

<script>
  let i, j;
  for(i = 0, j = 0; (i + j) < 5; i++, j += 1)
  {
    document.write("Hello JavaScript", "<br>");
  }
</script>

For Loop Statement having Compound Relation


The test condition in for statement can also have compound expression. Let’s take an example program based on it.

Program code 5:

<script>
  let x = 1, sum = 0;
  for(x = 1; x < 10 && sum < 10; x++){
    sum = sum + x;
  }
  document.write("Sum = " +sum);
</script>
Output:
      Sum = 10

In this example, the loop will execute until both conditions x < 10 and sum < 10 are true. The sum will evaluate within the body of loop.

Infinite For Loop in JavaScript


Consider the following example script code for infinite for loop statement in JavaScript.

<script>
  var x = 1;
  for(; ;)
  {
    document.write(x);
    x++;
  }
</script>

In this example, there is no test condition defined in the for statement that tells where to stop. As a result, the code will execute without stoppage. This loop is called an infinite loop in JavaScript. You should avoid to make an infinite loop.

By mistake, if you make infinite for loop in JavaScript program, you can stop it using the break statement. It will stop loop and come out of loop.

Let’s consider an example program based on infinite for loop where we will print the sum of squares of numbers from 1 to 10.

Program code 6:

<script>
  var i = 1;
  var sum = 0;
  for(; ;){
    sum = sum + i * i;
    i++;
    if(i >= 10) break; // If the i value exceeds 10, then the control will come out of this loop.
   }
  document.write("Sum: " +sum);
</script>
Output:
    Sum: 285

In this tutorial, you learned for loop statement in JavaScript with example programs. Hope that you will have understood the basic concepts of for loop and infinite for loop.

In the next tutorial, we will learn nested for loop statement in JavaScript with a variety of example programs.
Thanks for reading!!!
Next ⇒ Nested For Loops in JavaScript⇐ PrevNext ⇒