So I don’t know about you, but I am tired of writing the same ol’
for loops over and over again. Each time I have to write
i=0; i<somethingLong; i++, I think to myself (or mumble to my monitor), isn’t there a better way of doing this? Well yes there is! ES6 introduces
for...of and it’s time for us to level up our loops.
The goal of this post is to improve our knowledge base while encouraging us to utilize the new
for...of statement as we (continue to) advance our programming skills. So let’s upgrade from
forEach to the new hotness that is
Before we get started
The O.G. The foundation. The one, the only, the
for loops with
continue, we can skip to next iteration of the loop or terminate the current loop with
Introduced with ES5 is the
forEach method of the Array object. This method provides coding conciseness, allowing us to write less verbose statements.
Need the index and the array itself?
forEach has got you covered.
One of the downsides of the
forEach method, is that it does not support
continue. So what if you need to
break out of the loop or
continue to the next step?
for...of is the statement for you!
for...of statement provides us with the conciseness of
forEach with the feature richness (e.g.
continue) of the
for...in iterates over property names, while
for...of iterates through the values in the array.
Use destructuring to get key/value pairs
for...of we can obtain the feature richness of the classic
for loop, with the conciseness of the Array’s
Putting it all together, we can see the evolution from
So now that we have leveled up our loops, we are ready to go [for]th and program even more awesomeness! Check out the resources below and happy coding!