Leveling up our for
loops
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 for
to forEach
to the new hotness that is for...of
.
Before we get started
This article assumes you are familiar with for
statements and loops in general. MDN provides great overviews here and here.
Let’s loop!
for
The O.G. The foundation. The one, the only, the for
loop.
for
loops with break
and continue
Using continue
, we can skip to next iteration of the loop or terminate the current loop with break
.
forEach
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 break
and 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
The for...of
statement provides us with the conciseness of forEach
with the feature richness (e.g. break
and continue
) of the for
statement.
for...of
vs for...in
for...in
iterates over property names, while for...of
iterates through the values in the array.
Getting key
and value
with for...of
Use destructuring to get key/value pairs
Using for...of
with break
and continue
Conclusion
By using for...of
we can obtain the feature richness of the classic for
loop, with the conciseness of the Array’s forEach
method.
Putting it all together, we can see the evolution from for
to forEach
to for...of
.
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!
Additional Resources
- Loops and Iteration from Mozilla
for
,forEach
, andfor...of
by exploringjsArray.prototype.forEach
from Mozillafor...of
from Mozillafor...of
vsfor...in
on stackoverflow