For Loops in JavaScript

For Loops in JavaScript

Since Loop statements enable a particular code/block of code to be executed repetitively or repeatedly, as long as the stated condition is still being met. A For Loop iterates (i.e. executes a block of code repeatedly) over a specified number of times which is known beforehand.

for(initialization;condition;final-expression) {
    // block of code to be executed
}

For loop Components:

  • Initialization:

    This is the starting point of the for loop, and it is usually an assignment statement.

    E.g.

    If you want your loop to start from zero, you would have:

      let i = 0;
    
  • Condition:

    This determines if the loop should continue to run or not. It is a conditional statement, i.e. returns TRUE or FALSE.

    So, if it returns TRUE, the loop keeps on running, whereas if it returns FALSE, the loop ends.

    E.g.

    For 3 loops:

    T T T F

  • Final -Expression:

    This component runs at the end of the iteration before the loop goes back to the beginning, It is usually an increment statement (i.e. it increments the value that was assigned in the initialization component).

    E.g.

      // To increment variable i by 1
      i = i + 1;
      // To increment variable i by 2
      i = i + 2;
    
  • Block of code:

    This component gets executed every time the condition returns TRUE.

For Loop example:

Execute a block of code 3 times.

Solution:

Get the first 3 components

  1. Initialization:

     // Assume zero is starting point
     let i = 0;
    
  2. Condition:

    ???

  3. Final-expression:

     // increment by 1
     i = i + 1;
    

    For 3 loops, we need:

    T T T F

To get the Condition:

We start the value of i from zero, and we increment it by 1 at each turn till we get a FALSE, i.e.

0 (which is less than 3, so is TRUE)

0 + 1 = 1 (which is less than 3, so is TRUE)

1 + 1 = 2 (which is less than 3, so is TRUE)

2 + 1 = 3 (which is not less than 3, so is FALSE)

  • Condition (2nd component):

      i < 3;
    

    So, collecting the 3 components, we have:

      for(let i = 0; i < 3; i = i + 1) {
         // block of code
      }
    

Exercise:

Write a program that prints "Hello" five times. Assume the starting point is 2, and you are to increment by 2.

Solution:

Initialization:

let i = 2;

Condition:

2 ( first "Hello" is printed, so is TRUE)

2 + 2 = 4 (second "Hello" is printed, so is TRUE)

4 + 2 = 6 (third "Hello" is printed, so is TRUE)

6 + 2 = 8 ( fourth "Hello" is printed, so is TRUE)

8 + 2 = 10 (fifth "Hello" is printed, so is TRUE)

Remember, the program should print "Hello" five times, and since we have gotten that already, any increment now will be FALSE, i.e.

10 + 2 = 12 (sixth "Hello" is printed, so is FALSE)

// for us to get a result of TRUE
i < 12;

Final-Expression:

i = i + 2;

Our program therefore will be

for(let i = 2; i < 12; i = i + 2) {
   console.log("Hello");
};