For-of Loop

Other Loops

For-of Loop

🙋 Need help? Ask an expert now!

The for-of loop is similar to the for-in loop, but can only be used for arrays. The for-of loop iterates over the elements in an array and is a rather new loop in JavaScript. However, the for-of loop is part of the ECMAScript 6 standard and is supported by all modern browsers. Again, it is a rather advanced loop that might not be necessary or suited for you. The for loop can achieve the exact same results as the for-of loop if used correctly.

The syntax for the for-of loop is very similar to the for-in loop as shown above. The only difference is that instead of var index in arr, it's var index of arr. Since the for-of loop can only be used for an array, the use case of this loop is limited, meaning you might never have to use it in the future. However, it is a great loop that can simplify the code as the for-of loop is much cleaner than the for loop. Then again, there is no difference between using a for-of loop and a for loop or a while loop, so it is up to you to decide what's best for you. Be sure to revisit this loop after learning more about arrays.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [1, 2, 9, 16, 25];
let varOne = 0;
for (var index of arr) {
    if (index % 2 == 0){
        varOne += index;
    }
}
console.log(varOne);

What will the following code segment print to the console?