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.

javascript
1for (<initiate_variable>; <condition>; <update_variable>) {
2  . . .
3}

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.

javascript
1let n = 0;
2let result = 1;
3
4while (n < 10) {
5  result *= 2;
6  n++;
7}
8
9console.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.

javascript
1let result = 1;
2
3for (let n = 0; n < 10; n++) {
4  result *= 2;
5}
6
7console.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.

javascript
1let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2
3for (let i = 0; i < a.length; i++) {
4  if (a[i] === 5) {
5    console.log("Number 5 is found in the array.");
6  }
7}

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.

javascript
1let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2
3for (let i = 0; i < a.length; i++) {
4  if (a[i] === 5) {
5    console.log("Number 5 is found in the array.");
6    break;
7  }
8}

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.

javascript
1let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2
3for (let i = 0; i < a.length; i++) {
4  if (a[i] % 2 === 0) {
5    continue;
6  }
7
8  console.log(a[i]);
9}
text
11
23
35
47
59

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.