⚖️for-of vs. forEach
JS⟩ syntax ⟩ for loops ⟩ for-of ⟩ vs. forEach
Don't use forEach. (In fact, never use forEach anywhere in ES6).
forEach has known pitfalls that make it unsuitable in some situations that can be properly handled with for or for-of:
callback function creates new context (can be addressed with arrow function)
doesn't support iterators
doesn't support generator
yieldandasync..awaitdoesn't provide a proper way to terminate a loop early with
break
"holes" in sparse arrays are treated differently in for-of and forEach.
for-of:"holes" are treated as undefined.
forEach:"holes" are ignored.
let a = []; // sparse array
a[1] = 'hi';
a[5] = 'world';
let forofCount = 0;
let foreachCount = 0;
// ⭐️ for-of: treats "holes" as `undefined`.
for (const value of a) {
forofCount += 1;
console.log(forofCount, value);
}
// 1 undefined, 2 'hi', 3 undefined, ... 6 'world'
// ⭐️ forEach: ignores "holes".
a.forEach(value => {
foreachCount += 1;
console.log(foreachCount, value);
})
// 1 'hi', 2 'world'Last updated
Was this helpful?