For Loops in JavaScript

Notice that in our previous examples with while loops, every time we create a loop, we must initiate a variable, and then create a condition for the loop. When the condition is violated, the loop will stop. And inside the loop, the variable is updated for every iteration.

For loop

The for loop is essentially a shortcut that allows you to define all of the above in one line of code.

for (<initiate_variable>; <condition>; <update_variable>) {
  . . .
}

Every while loop can be rewritten into a for loop. For example, let's do something more interesting this time. The following while loop computes 2 to the power of 10.

let n = 0;
let result = 1;

while (n < 10) {
  result *= 2;
  n++;
}

console.log(result);

This loop iterates ten times, and for each iteration, result is updated to 2 times itself.

You can restructure this while loop into a for loop, which does the exact same thing.

let result = 1;

for (let n = 0; n < 10; n++) {
  result *= 2;
}

console.log(result);

How to break out of a loop

Consider this problem, you are iterating over an array of numbers to find the number 5.

let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (let i = 0; i < a.length; i++) {
  if (a[i] === 5) {
    console.log("Number 5 is found in the array.");
  }
}

This loop will be terminated when i reaches the last index of the array. But, imagine this array has one million elements, the program will go over the entire array even after it has found the number 5, which is highly inefficient.

To fix this issue, we need a different way to break out of this loop. Luckily, JavaScript offers us a solution, the break keyword.

let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (let i = 0; i < a.length; i++) {
  if (a[i] === 5) {
    console.log("Number 5 is found in the array.");
    break;
  }
}

This way, when JavaScript finds the number 5, the if statement will be executed, and when it encounters a break, the loop will terminate.

Besides break, there is another keyword called continue. It works similarly to break, except continue breaks out of the current iteration, not the entire loop.

let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (let i = 0; i < a.length; i++) {
  if (a[i] % 2 === 0) {
    continue;
  }

  console.log(a[i]);
}
1
3
5
7
9

This time, the loop will again iterate over the entire array, and if the array element is an even number (a[i] % 2 === 0), the keyword continue will execute, and JavaScript will start the next iteration, ignoring the rest of the code block. As a result, this example will print out all odd numbers in the array.