4 ms·
I find "for of" to be much more legible than "forEach". Not much difference in general but the "for" the beginning immediately tells me that there is a loop her
by mschuetz 9y ago
I find "for of" to be much more legible than "forEach".
Not much difference in general but the "for" the beginning immediately tells me that there is a loop here, whereas I have to read more thoroughly to identify something as a loop in the forEach case.
// for ... of
for(let node of nodes){
console.log(node);
}
// forEach
nodes.forEach(node => {
console.log(node);
});
- Klathmon 9y agoFor...of is fantastic and I use it quite often (especially in async/await codebases as it doesn't create a new function context!) However it is slow currently in all major browser engines. For fast-path code, you should reach for something else (like a for(;;) loop), but for most other loops I always tend to reach for for...of for it's ease of use and compatibility with iterators makes it a pleasure to use!
- mschuetz 9y agoAre you sure about that? "for of" is something that I'd expect a js compiler to handle exactly the same way as forEach. I'd see how it might have been slower right when it came out but browser vendors are quick in optimizing their compilers. At least https://jsperf.com/for-vs-foreach/293 https://jsperf.com/for-vs-foreach/293 shows that there is no significant difference in for of vs forEach in my version of chrome. There is an insignificant difference acoording to which forEach is actually slower. (One forEach case in that benchmark is only faster because it does something different.) Edit: looking at the comparison at the bottom, it seems like forEach is actually significant slower than for of since chrome 61.
- Klathmon 9y agoYa know what I'm not as sure as i thought I was. I'm really glad that for...of isn't nearly as slow as it was when it was first profiled it. Thanks for that!
- olliej 9y agoLots of work went into making the perf of for(of) fast - after the initial “make it semantically correct” bits. There are many reasons it is faster, but it also has the nice property of working sensibly on any iterable object rather than forEach that only iterates by index, and has an annoying ‘if (index in object)’ in the loop.
- phpnode 9y agofor of has got a lot faster recently but it's still never going to beat the performance of a normal for loop due to the semantics - each turn of the for of loop requires a new iterator object to be allocated.
- bryanrasmussen 9y agothe forEach is running a function on each node, passing the node as a parameter and console.logging that node. the for of is a loop. at any rate it seems the kind of difference in legibility that would vanish with very little familiarity, I would expect for most people developing JavaScript regularly that forEach would be more legible - even with the arrow function - because it is the construct they encounter and use more often day to day.