JavaScript for loop Complete Tutorial

In this section, we will learn what the for loop is and how to use it in JavaScript.

What is for Loop in JavaScript?

The `for ` loop is mainly used to repeat the execution of a set of instructions for a specific number of times.

We say mainly, because it is possible to run a `for` loop for infinite times (as long as it doesn’t crash the system).

JavaScript for Loop Syntax:

for (initialization_statement ; condition_statement ; update_statement) {
// the instructions within the body of 'for' loop
}

`for`: To create a `for` loop, we start with the keyword `for`.

`( )`: In a `for loop` there are three statements which two of them are optional. These statements can be set in the parentheses that come after the `for` keyword.

In short, these statements are for:

  1. The first statement: Declaring and initializing a variable (Optional).
  2. The second statement: Set a condition.
  3. The third statement: Update the variable that was created in the first statement (Optional).

`initialization_statements`: within a loop there’s a condition in which either a true or false will come out of that condition. For example, let’s say we have a variable named `counter` and its value is `0`. The condition in the loop could be to check and see if the value of the `counter` is equal to 10. Ignoring the condition for now, the variable and its value is a necessary part for the condition of the `loop` to run properly.

We could either create this variable outside of the loop or we have this option of creating the variable right in the first statement the `initialization_statement` which is actually the purpose of this statement.

Note: the first statement will only run once, and that is the time when the loop starts.

`condition_statemnet`: This is where we set the condition expression that results either true or false. As long as the result of this condition is true, the body of the loop will be executed over and over again.

Note: in `condition_statement` we can use comparison and logical operators to create complex conditions.

`update_statement`: the last statement within the parentheses `( )` is used to update the variable that is used in the `condition_statement`.

For example, if there’s a variable named `counter` and it is used in the condition statement like `counter < 10;` then we can use the third statement to increase the value of the `counter` variable by some.

Note: the last statement will run every time the for-loop is repeated.

`;`: the statements mentioned above are separated from each other via a semicolon `;`.

`{ }`: The body of the `for` loop is within the pair of braces that comes after the parentheses `( )`.

Here’s the order of execution in a `for` loop:

  1. Initialization statement.
  2. Condition statement.
  3. The body of the `for` loop.
  4. Update statement.

After the first 4 steps, as long as the result of the loop’s condition is true, the steps from 2-4 will be iterated.

Example: using for loop in JavaScript

for (let i = 0; i<10; i++){
    console.log(i);
}

Output:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

Here, the initialization statement is: `let i = 0;`

The condition of the loop is: `i<10;`

And the last statement which is the update statement is: `i++`

So the first step (initialization) will occur right when the execution engine enters the loop. After that the condition of the loop will be checked and because currently the value of the `i` is less than the value 10, the body of the loop will be executed.

After that, the third condition which is `i++` will run.

After the first round:

  1. First, the condition of the loop will be checked again.
  2. Second, if the result of the loop’s condition is true, the body of the loop will be executed.
  3. After that, the engine moves towards the execution of the update statement `i++`.
  4. The steps from 1 to 3 will be repeated as long as the result of the condition is true. After the result becomes false, the engine will leave the body of the loop and run the instructions after the loop.

JavaScript for Loop break: Exit from for loop in JavaScript

We can use the `break` statement in the body of a for loop to break its iteration as well.

Note: please check the break statement section if you’re not familiar with this statement.

Example: using break statement in JavaScript for loop

const multi = [1,2,3,4,5,6];
for (let i = 0; i<multi.length; i++){
  if (multi[i]>4){
    break;
  }
  console.log(multi[i]);
}

Output:

1

2

3

4

JavaScript for Loop continue

We can use the `continue` statement in the body of a for loop to skip the iteration of the current loop and move to the next iteration.

Note: please check the continue statement section if you’re not familiar with this statement.

Example: using continue statement in JavaScript

const multi = [1,2,3,4,5,6];
for (let i = 0; i<multi.length; i++){
  if (multi[i]<4){
    continue;
  }
  console.log(multi[i]);
}

Output:

4

5

6

Infinite Loop in JavaScript via for Loop

As mentioned at the beginning of this section, we can run an infinite loop via `for` loop as well.

Here’s how to do so:

Example: creating infinite for loop in JavaScript

let i = 0;
for (; true; ) {
    i++;
    console.log(i);
    if (i == 20) {
        break;
    }
}

Output:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,

Here, because there’s no update statement, we need to define a breakpoint in the body of the loop itself.

So we used the `if` and `break;` statements to define this break point.

Basically, when the value of the `i` variable reaches to the value 20, the body of the `if` statement will run and after the `break;` statement, the execution engine will leave the body of the loop and continue to run the instructions after the loop.

Example: looping through a multidimensional array via for loop

const multi = [
  [1,2,3,4,5,6],
  ["Omid","Jack","John"]
];
for (let i =0 ; i<multi.length; i++){
  for (let b = 0; b<multi[i].length; b++){
    console.log(multi[i][b]);
  }
}

Output:

1

2

3

4

5

6

Omid

Jack

John

The important note to remember about a multidimensional array is that you’ll need a nested for loop per each sub-array if you want to get the final element of the final sub-array.

So here the array was a 2D array and so we’ve used 2 for-loops in order to iterate through the entire elements of the sub-arrays.

Basically, the first for loop iterates through the first array (multi) and the second for loop will iterate through the elements of the sub-arrays.

while Loop vs for Loop

Both `for-loop` and while-loop are capable of running a block of code for x number of times, but the design of `for loop` is more focused towards creating loops that should run for a specific number of times. On the other hand, the `while` loop is designed to run a block of code as long as a condition is met! So the number is not of the focus when using the `while` loop.

Note: remember, both while and for loop still are capable of doing the same tasks, but their main difference is in the design purpose.

More to read:

JavaScript for of loop

JavaScript for in loop

JavaScript while loop

Leave a Reply