For Each Loop in JavaScript: Mastering forEach and for...of

A practical, developer-focused guide to iterating with forEach and for...of in JavaScript, covering syntax, async patterns, pitfalls, and best practices for aspiring developers.

JavaScripting
JavaScripting Team
·5 min read
ForEach in JS - JavaScripting
Quick AnswerDefinition

JavaScript does not have a dedicated 'for each' keyword. Instead, you typically iterate over arrays using Array.prototype.forEach or the for...of loop. Each approach applies a function to every element or yields each element in sequence, respectively. For simple side effects, forEach is concise; when you need early exit, break/continue, or proper async handling, for...of is usually the better choice. This guide covers both patterns with practical examples.

Understanding the two main patterns for per-item iteration in JavaScript

JavaScript offers multiple ways to loop over a collection. The two most common patterns are Array.prototype.forEach and the for...of loop. Each approach has strengths and trade-offs depending on your goal. Use forEach for a concise, functional style when you only need to apply a side effect to every element. Use for...of when you need explicit control flow, early exit, or compatibility with async/await patterns.

To get started, consider a simple array of numbers:

JavaScript
const nums = [1, 2, 3, 4];

Now see how each pattern handles iteration:

JavaScript
// forEach pattern nums.forEach((n, idx) => { console.log(`idx=${idx} value=${n}`); });
JavaScript
// for...of pattern for (const n of nums) { console.log(`value=${n}`); }
  • Key takeaways:
    • forEach executes a callback for every element; it cannot be stopped with break, and it does not support async/await directly inside the callback.
    • for...of yields each element and supports break/continue; it integrates naturally with async/await when wrapped inside an async function.

This overview sets the stage for deeper examples in the next sections, including asynchronous iteration and data transformation tasks.

],

prerequisites

Steps

Estimated time: 45-60 minutes

  1. 1

    Define the iteration goal

    Identify whether you need side effects, transformation, or a mix. Decide if you require early exit, and whether asynchronous operations will occur. This clarifies whether forEach or for...of is appropriate.

    Tip: Start by writing a tiny example to observe differences in behavior.
  2. 2

    Write a forEach snippet

    Implement a simple forEach to apply a function to every element. Verify that you cannot break out of the loop from inside the callback.

    Tip: Remember that the callback controls the per-element work, not the outer function.
  3. 3

    Switch to for...of when needed

    If you anticipate needing break/continue or awaiting inside the loop, rewrite using for...of and, if needed, wrap awaits in an async function.

    Tip: For async work, consider sequential vs parallel strategies.
  4. 4

    Handle async operations

    Decide between sequential (for...of with awaits) and parallel (Promise.all with map) patterns. Implement error handling and timeouts if necessary.

    Tip: Avoid awaiting inside forEach; use for...of or Promise.all.
  5. 5

    Refactor and test

    Run unit tests or console checks to ensure behavior matches expectations across edge cases (empty arrays, single-element arrays, large datasets).

    Tip: Benchmark critical paths if performance matters.
Pro Tip: Prefer forEach for simple side effects; use for...of when break/continue or async control flow is needed.
Pro Tip: Map is the go-to for pure transformations; use forEach only when you’re mutating external state or building another structure.
Warning: Do not rely on break in forEach; use for...of if you need early exit.
Note: As with any loop, consider readability and team conventions when choosing between patterns.

Prerequisites

Required

Optional

  • Familiarity with async/await
    Optional
  • Optional knowledge of Array methods like map, filter, reduce
    Optional

Keyboard Shortcuts

ActionShortcut
CopyCopy selected textCtrl+C
PastePaste into code editorCtrl+V
Find in fileSearch text in the current fileCtrl+F
Format documentAuto-format code in editor+Alt+F
Toggle line commentComment/uncomment selected linesCtrl+/

Questions & Answers

What is the main difference between forEach and for...of in JavaScript?

The forEach method runs a callback for each array element and cannot be broken out of with a standard break. The for...of loop yields each element and supports break, continue, and easy integration with async/await when used inside an async function.

ForEach runs a callback for every element and can’t be broken out of, while for...of lets you break and use awaits inside the loop.

Can I break out of a forEach loop?

No, not from the outside. The only way to stop early is to throw an exception or re-think the approach and use a for...of loop or a manual index-based loop.

No, you can’t break out of forEach; use a for...of loop if you need early exit.

Is forEach asynchronous-friendly?

The forEach callback does not inherently handle async/await in a way that waits for each iteration. If you need sequential async work, use for...of inside an async function or collect promises and await them with Promise.all.

forEach isn’t ideal for awaiting inside; prefer for...of or Promise.all.

When should I use map instead of forEach?

Use map when you want to transform an array into a new array. forEach is better for side effects or when you’re mutating an external structure, but map conveys intent more clearly for transformations.

Use map for transformations; forEach is for side effects.

Do forEach or for...of affect performance?

Performance differences are usually negligible for typical UI tasks. Readability and correctness matter more; optimize only if you have measurable bottlenecks.

Performance is usually not a deciding factor; readability comes first.

How can I iterate over object properties with these patterns?

Convert objects to arrays with Object.keys/values/entries and then use forEach or for...of on the resulting array. For example, Object.values(obj).forEach(v => ...).

If you need to loop over object values, convert to an array first and then apply your loop.

What to Remember

  • Choose forEach for concise side effects
  • Use for...of when you need break/await
  • Prefer map for transformations
  • Avoid mutating the source during iteration
  • Async work often benefits from for...of or Promise.all

Related Articles