⚖️for-of vs. forEach

JSsyntaxfor loopsfor-of ⟩ vs. forEach

always use for-of in ES6.

  • It works on any iterable

  • 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

Last updated