Thanks for the great read! It's always interesting seeing other peoples perspectives on it.
I feel like forEach is in this weird space between for of and the more functional operators map/reduce. Almost every use case for looping over an array is to change its shape, either by manipulating each item (which makes map ideal) or by aggregating the array contents (which makes reduce ideal).
Using your key/value map example, I would typically use reduce as follows:
It's very similar, but has notably fewer side effects. You can also make it really terse, if that's your kind of thing, and if you use the spread operator to shallow copy you can reduce the footprint for unintentional side effects even further:
Thanks for the great read! It's always interesting seeing other peoples perspectives on it.
I feel like
forEach
is in this weird space betweenfor of
and the more functional operatorsmap/reduce
. Almost every use case for looping over an array is to change its shape, either by manipulating each item (which makesmap
ideal) or by aggregating the array contents (which makesreduce
ideal).Using your key/value map example, I would typically use
reduce
as follows:It's very similar, but has notably fewer side effects. You can also make it really terse, if that's your kind of thing, and if you use the spread operator to shallow copy you can reduce the footprint for unintentional side effects even further:
Just some thoughts. :)
Thanks for this insightful explanation @mikegeyser !
It's true that if I'm using
.forEach
quite often, it's worth considering using more "specialised" methods such as.reduce
.Which is a great transition to announce the topic for the next article of this series:
Array.prototype.reduce
!Stay tuned! ✌