DEV Community

Cover image for Strength of for-of loop over for-in and foreach loops in ES6.
Nsengiyumva Gershom La paix
Nsengiyumva Gershom La paix

Posted on • Updated on

Strength of for-of loop over for-in and foreach loops in ES6.

Iterators are helpful to know because they serve as the basis for generators, which open new doors to asynchronous programming. ES6 came with for-of loop to beat some pitfalls found for-in loop.

Some drawbacks which are found in for-in loop:

1.The values assigned to the index are the strings, not actual numbers.
Look here:

var arr = [111, 222, 333];
for(var i in arr) {
    if(i === 1) {
        // Never execute
    }
Enter fullscreen mode Exit fullscreen mode

2.for-in loop can iterate over the array elements in the arbitrary order.
3.In foreach loop, we can't break out of the loop using break statement. Another drawback is that no returning from the enclosing function using return statement.

What for-of loop holds for us?

1.It avoids all pitfalls of for-in loop and works with
break, continue and return statements.
Here is an example:

for (var num of arr) {
    if (num % 2 == 0) {
        continue;
    }
    console.log(num)
}
Enter fullscreen mode Exit fullscreen mode

2.It also works on strings, where it treats strings as a sequence of Unicode characters

for (var ch of "😺😲") {
    console.log(ch);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Fellow guys, now I can recommend you to use this syntax sugar of for-of loop as it can help us in most cases. But, if you find some cases where you need such for-in and foreach loops, don't hesitate to use them as they are still useful.

Thank you!!!

Top comments (0)