JS⟩ syntax ⟩ for loops ⟩ for-of ⟩ vs. forEach
always use for-of
in ES6.
It supports all kinds of control flow in the loop body, like continue
, break
, return
, yield
and await
.
👉 stackoverflow
Don't use forEach
. (In fact, never use forEach
anywhere in ES6).
👉 stackoverflow
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 yield
and async..await
doesn't provide a proper way to terminate a loop early with break
👉 stackoverflow
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'