// for ... of
for(let node of nodes){
console.log(node);
}
// forEach
nodes.forEach(node => {
console.log(node);
}); // for ... of
for(let node of nodes){
console.log(node);
}
// forEach
nodes.forEach(node => {
console.log(node);
});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!
At least 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.
Thanks for that!
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.
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.