4 ms·
While I agree on the side-effect side of things, you really shouldn't use a classic for loop when forEach suffices. forEach emphasizes you are operating on eac
by geokon 5y ago
While I agree on the side-effect side of things, you really shouldn't use a classic for loop when forEach suffices.
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"
- ablu 5y agoI think `for element of list` nowadays starts to become a realistic choice (without a transpiler) for that: https://caniuse.com/?search=for...of https://caniuse.com/?search=for...of
- cehrlich 5y agoAs an added benefit, `for...of` works with async, unlike forEach.
- dragonwriter 5y agoIf I would be tempted to use forEach but can’t because async, I usually don’t want for…of semantics, though. I probably want something like await Promise.all(collection.map(thing => some_async_function(thing))); instead of: for thing of collection { await some_async_function(thing); }
- mnahkies 5y agoThe index and the collection iterated over is passed as the 2nd/3rd parameters in JavaScript, so technically you still have access to them, though in the majority of cases people will omit these parameters
- dragonwriter 5y ago> The index and the collection iterated over is passed as the 2nd/3rd parameters in JavaScript, 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.
- _notathrowaway 5y ago>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. 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.
- geokon 5y agooh yikes sorry. I didn't realize JavaScript is so idiosyncratic. i was just kinda thinking from my c++ bubble i guess