JavaScript For Loop

The JavaScript For Loop is used to repeat a block of statements a number of times until the given condition is False. It is one of the most commonly used ones. This blog post will explore the JavaScript For Loop syntax, simple examples, iteration processes, practical applications, and advanced techniques to optimize performance.

In JavaScript for loop, there are three expressions separated by semicolons (;), and the execution of these expression components is as follows:

  • Initialization: Javascript For loop starts with the initialization statement. So, the initialization of counters variables is done first (For example, counter = 1 or i=1.). The initialization section is executed only once at the beginning before the loop starts.
  • Test Condition: The value of the counter (initialized) variable will test against the given condition. If it is True, it will execute the statements inside it. If it evaluates to false, the JavaScript For loop will terminate, and the control passes to the following line after the loop.
  • Expression to update Counter Value: This expression will execute after the end of each iteration and is responsible for updating the counter variable. The Increment and decrement operator helps to increase or decrease the counter variable, as per our requirement.

JavaScript for loop Syntax

The syntax of the JavaScript for loop is as shown below.

for (initialization; test condition; Expression to update counter value)
 {
    //Statement 1
    //Statement 2
     ………
    //Statement n
 }

Let me explain the Initialization, Test condition, and Expression to update Counter Value with a simple example.

for(i = 1, i <= 10, i++)
{
	// Statements to Execute for each iteration.
}

In this JavaScript example, initialization sets the initial value of the for loop. So, i = 1 is the initialization executed before the loop begins.

The test condition is i <= 10. This condition will check before each iteration with an updated i value (step 3). If the condition i <= 10 evaluates true, the code within the curly braces will execute. If i <=10 is false, the loop will terminate. The loop will continuously run as long as the i value is less than or equal to 10. Remember, it becomes an infinite loop if you forget to update the i value.

The expression to update the counter value is i++. It means after each iteration, i value will increment by 1. So, the condition i <= 10 will test with this new value. Similarly, you can try i–, i + 2, i – 2, etc.

This process repeats until i becomes 11, and the condition 11 <= 10 evaluates to false, at which point the loop terminates. Next, the program continues executing the remaining code.

JavaScript For Loop Example

This program allows the user to enter any integer values. The JavaScript for loop program will calculate the sum of natural numbers up to the user entered number.

<!DOCTYPE html>
<html>
<head>
    <title> Example</title>
</head>

<body>
    <h1> JS example </h1>
<script>
    var i, number = 10, total = 0;
    for (i = 1; i <= number; i++)
    {
        total = total + i;
    }
    
    document.write("<b>Sum of N Natural Numbers is </b>= " + total);  
</script>
</body>
</html>
JavaScript For Loop 1

Analysis

  1. In this JavaScript For Loop example, First, We declared the number variable and assigned the value of 10, and the total variable will initialize to 0.
  2. Next, we will check whether the counter variable (i) is less than or equal to a number.
  3. If the condition results are true, i added them to the total. Otherwise, it will exit from it. At the start of it, i =1 and n =10, so the condition will be True until i value is incremented to 11.
  4. In the next section, we used the ++ operator to increment the i value. After the incrementing process, it will repeat the process until the expression results as False (until I =11).

JavaScript For Loop Features

The For loop in JavaScript has the flexibility to omit one or more sections from the declaration. Although we can skip one or more sections from it, we must put the semicolon (;) in place; otherwise, it will throw a compilation error.

Initialization of the counter variable can skip in JavaScript For Loop.

int i=1;

for( ;i<=10;i++)

Here, the counter variable is declared before.

Like initialization, we can skip the increment part because the incrementing part declares inside the body.

int i=1;

for( ;i<=20; )
 {
   //statements     
   i++;
 }

JavaScript For loop allows us to initialize more than one counter variable at a time with comma separate:

for(i=1,j=20; i<j; i++)

It also allows using multiple conditions. Instead of using a comma, we have to use the logical operator to separate the two condition

for(i=1,j=20; i<=10 && j>=20; i++)
 {
   //statements
   j++;
 }

Like the test condition, JavaScript for loop allows us to use more than one increment operator as follows

for(i=1,j=1; i<=10 && j<=10; i++, j++)

NOTE: For the initialization, increment, and decrement operator section, we can use commas to separate multiple declarations. To separate the test conditions, you must use a Logical Operator to join conditions.

Nested For Loop in JavaScript

We will nest one for loop inside another, called nested for loop.

<!DOCTYPE html>
<html>
<head>
    <title> Nested </title>
</head>

<body>
    <h1> JS Nested </h1>
<script>
    var i, j;
    for (i = 9; i <= 10; i++)
    {
        for (j = 1; j <= 10; j++)
        {
            document.write(i + "*" + j + "=: " + (i * j) + "<br \>"); 
        }
    }   
</script>
</body>
</html>
JS Nested
9*1=: 9
9*2=: 18
9*3=: 27
9*4=: 36
9*5=: 45
9*6=: 54
9*7=: 63
9*8=: 72
9*9=: 81
9*10=: 90
10*1=: 10
10*2=: 20
10*3=: 30
10*4=: 40
10*5=: 50
10*6=: 60
10*7=: 70
10*8=: 80
10*9=: 90
10*10=: 100

The above program for JavaScript For Loop example will print multiplication tables for 9 and 10. First, i initialized to value nine, and then it will check whether i is less than or equal to 10. This condition is True until i reach 11. Then, if this condition is True, it will enter the second one. Otherwise, it will exit.

In the second JavaScript for loop, j initializes to value 1. Next, it will check whether i is less than or equal to 10. This condition is True until i reach 11.

Iteration 1: i = 9, and the condition is True. So entered the second one. j =1 and j <=10 condition is True, so the statement inside the loop is printed

9 * 1 = 9

Now the value of j will increment to 2

9 * 2 = 9

it will repeat the process up to 10.

Now the value of j is 11, and the condition fails so that it will exit from the second. However, it will only exit from the inner or Second but not from the entire loop.

Iteration 2: i = 10, and the condition is True, so repeat the above process

Iteration 3: i = 11, and the condition is False. So, JavaScript For loop terminates. No need to check the second one.