JavaScript for Loop

JavaScript includes for loop like Java or C#. Use for loop to execute code repeatedly.

Syntax:
for(initializer; condition; iteration)
{
    // Code to be executed
}

The for loop requires following three parts.

  • Initializer: Initialize a counter variable to start with
  • Condition: specify a condition that must evaluate to true for next iteration
  • Iteration: increase or decrease counter
Example: for loop
for (var i = 0; i < 5; i++)
{
    console.log(i);
}
Output:
0 1 2 3 4

In the above example, var i = 0 is an initializer statement where we declare a variable i with value 0. The second part, i < 5 is a condition where it checks whether i is less than 5 or not. The third part, i++ is iteration statement where we use ++ operator to increase the value of i to 1. All these three parts are separated by semicolon ;.

The for loop can also be used to get the values for an array.

Example: for loop
var arr = [10, 11, 12, 13, 14];

for (var i = 0; i < 5; i++)
{
    console.log(arr[i]);
}
Output:
10 11 12 13 14

Please note that it is not mandatory to specify an initializer, condition and increment expression into bracket. You can specify initializer before starting for loop. The condition and increment statements can be included inside the block.

Example: for loop
var arr = [10, 11, 12, 13, 14];
var i = 0;

for (; ;) {
    
    if (i >= 5)
    break;

    console.log(arr[i]);
        
    i++;
}
Output:
10 11 12 13 14

Learn about while loop in the next section.

Points to Remember :
  1. JavaScript for loop is used to execute code repeatedly.
  2. for loop includes three parts: initialization, condition and iteration. e.g.for(initializer; condition; iteration){ ... }
  3. The code block can be wrapped with { } brackets.
  4. An initializer can be specified before starting for loop. The condition and increment statements can be included inside the block.
Want to check how much you know JavaScript?