TIL the history of the for, forEach, and for...of loops
POSTED ON:
TAGS: arrays javascript
First, we had the for
loop.
The problem with for
loops are:
- off-by-one errors
- A chance to create infinite loops
- Statefulness
- hidden intent
IT's explained here 4 Reasons Not to Use Programming Loops (and a Few Ways to Avoid Them)
Then, we had the forEach
loop.
This new version was introduced in 2009 with Ecmascript 5.
It solved a bunch of problems. It's a fine solution.
Finally, we have the for ... of
loop.
As new objects like set
, map
were created, they needed a solution.
forEach
only works on arrays
.
for ... of
works on:
- Array
- Map
- Set
- String
- TypedArray
- Other W3C classes
It supports all kinds of control flow in the loop body, like continue
, break
, return
, yield
and await
.
Resources:
https://stackoverflow.com/questions/50844095/should-one-use-for-of-or-foreach-when-iterating-through-an-array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
Related TILs
Tagged: arrays