by geokon · 4y ago · 0 comments
forEach emphasizes you are operating on each element of the loop in a semi-independent fashion and you explicitly don't have access to any kind of intermediary index/iterator variable.
When you "drop down" to a classic for loop you're telling the reader that you need access to the index/iterator for some reason (and there are plenty of valid reasons for that).
If you only use classic for loops then the reader has to be constantly vigilant you're not doing any index/iterator shenanigans. It's just higher "cognitive load"
I disagree with this point, specifically for JavaScript the for...of syntax is more pleasant to read and also does not infer that any index access is gonna be done. And as a plus, it is easier to be used with async/await.
await Promise.all(collection.map(thing => some_async_function(thing)));
instead of: for thing of collection {
await some_async_function(thing);
}Yeah, the “map and friends pass extra parameters that are usually ignored” plus the “lots of JS functions optionally take extra parameters that are usually unused” makes it so easy to think of a function as a one-arg function when its really one plus multiple optionals, use it bare in a map, and get stung by it.