JavaScript Array forEach() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Iterate

What You’ll Learn

The forEach() method runs a function on every array element for side effects—logging, summing into a variable, updating the DOM. It returns undefined, unlike map(). This tutorial covers syntax, five examples, when to choose forEach over other loops, and common pitfalls.

01

Syntax

forEach(fn)

02

Side effects

Not a mapper

03

Returns

undefined

04

No break

Use for loop

05

Index + array

Callback args

06

ES5

Wide support

Introduction

Loops are everywhere in JavaScript. The forEach() method gives you a clean, readable way to visit each element without writing index variables or managing loop conditions manually.

Use it when you want to do something with each item (log it, push to another array, update UI)—not when you need a transformed array back. For that, reach for map() or filter().

Understanding the forEach() Method

array.forEach(callback) calls your callback once per element, passing (element, index, array). The callback runs in ascending index order from 0 to length - 1.

The method itself always returns undefined. Any result you need must be stored in an outer variable or performed as a side effect (like writing to the console or DOM).

💡
Beginner Tip

You cannot break out of forEach. If you find yourself wanting to stop early, switch to for...of or a classic for loop with break.

📝 Syntax

General form of Array.prototype.forEach:

JavaScript
array.forEach(callback(element, index, array), thisArg)

Parameters

  • callback — function run for each element.
  • element — current value in the callback.
  • index — current index (optional in callback signature).
  • array — the array being iterated (optional third callback arg).
  • thisArg — optional this value inside the callback.

Return value

  • Always undefined.
  • Does not create a new array.
  • Skips empty slots in sparse arrays.

Common patterns

  • arr.forEach((x) => console.log(x)) — log each item.
  • arr.forEach((n) => { sum += n; }) — accumulate in outer variable.
  • arr.forEach((item, i) => { ... }) — use index when needed.
  • arr.forEach(fn, context) — bind this with thisArg.

⚡ Quick Reference

GoalCode
Run code on each elementarr.forEach(fn)
Return valueundefined
Build new arrayUse map() instead
Break earlyUse for or for...of
Skip sparse holes?Yes

📋 forEach() vs map() vs for...of vs for loop

Choose forEach for readable side-effect loops; use others when you need return values or control flow.

forEach
side effects

Returns undefined

map
new array

Transform data

for...of
break/continue

Modern loop

for
full control

Index + break

Examples Gallery

Open DevTools Console (F12) or use Try-it labs. Example N maps to ?tryit=N.

📚 Getting Started

Basic iteration and accumulation.

Example 1 — Log Each Element

The simplest use: run a function for every item in the array.

JavaScript
const fruits = ["apple", "banana", "cherry"];

fruits.forEach((fruit, index) => {
  console.log(index, fruit);
});
// 0 apple
// 1 banana
// 2 cherry
Try It Yourself

How It Works

The callback receives the element and its index. Perfect for debugging or printing lists.

Example 2 — Sum Array Elements

Accumulate a total in an outer variable—a classic forEach pattern.

JavaScript
const numbers = [1, 2, 3, 4, 5];
let sum = 0;

numbers.forEach((num) => {
  sum += num;
});

console.log(sum);
// 15
Try It Yourself

How It Works

forEach does not return the sum—you update sum inside the callback. For reductions, reduce() is often cleaner.

📈 Practical Patterns

Build arrays, compare methods, iterate objects.

Example 3 — Build a New Array Without Mutating

Push doubled values into a separate array instead of modifying the source.

JavaScript
const numbers = [1, 2, 3, 4, 5];
const doubled = [];

numbers.forEach((num) => {
  doubled.push(num * 2);
});

console.log(doubled);
// [2, 4, 6, 8, 10]
Try It Yourself

How It Works

This works, but map((n) => n * 2) is the idiomatic way to produce a new array. Use forEach when side effects are the main goal.

Example 4 — forEach() Returns undefined

See why you cannot chain or assign the result of forEach like map.

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

const fromMap = nums.map((n) => n * 10);
const fromForEach = nums.forEach((n) => n * 10);

console.log("map:", fromMap);
// [10, 20, 30]

console.log("forEach:", fromForEach);
// undefined
Try It Yourself

How It Works

map collects return values from the callback. forEach ignores callback return values entirely.

Example 5 — Iterate an Array of Objects

Process structured data—common in UI and API handling.

JavaScript
const users = [
  { name: "Alex", role: "admin" },
  { name: "Sam", role: "editor" }
];

users.forEach((user) => {
  console.log(`${user.name} (${user.role})`);
});
// Alex (admin)
// Sam (editor)
Try It Yourself

How It Works

Each object is one element. The callback reads properties and performs actions like logging or DOM updates.

🚀 Common Use Cases

  • Console logging — inspect each element during development.
  • DOM updates — create or update nodes for each list item.
  • Accumulating totals — sum, count, or aggregate in outer variables.
  • API side effects — send analytics or fire requests per item.
  • Validation passes — check each entry and collect errors manually.
  • Event setup — attach listeners to each element in a NodeList converted to array.

🧠 How forEach() Runs

1

Start at index 0

Loop while index < array.length.

Init
2

Skip holes

Empty slots in sparse arrays are not visited.

Sparse
3

Invoke callback

Pass element, index, and the array reference.

Call
4

Return undefined

All side effects live inside the callback.

📝 Notes

  • Return value is always undefined—not chainable like map.
  • break and continue do not work; use a for loop instead.
  • return in the callback only exits that one iteration.
  • Avoid adding/removing items while iterating—can cause skipped or duplicate visits.
  • Prefer reduce() for sums; filter() for conditional lists.
  • ES5—excellent browser support including IE9+.

Browser & Runtime Support

Array.prototype.forEach() has been available since ES5 (2009). It is one of the most widely supported array methods.

Baseline · ES5

Array.prototype.forEach()

Supported in Chrome 1+, Firefox 1.5+, Safari 3+, Edge (all versions), IE 9+, and all modern Node.js versions.

99% Universal support
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
Array.forEach() Excellent

Bottom line: Safe to use everywhere except very old IE8 environments. No polyfill needed for modern projects.

Conclusion

forEach() is the readable choice when you need to run code on every array element without building a new array. Remember it returns undefined and cannot be broken out of early.

When you need to check membership instead of iterating, the next method to learn is includes().

💡 Best Practices

✅ Do

  • Use forEach for side effects (log, DOM, API calls)
  • Keep callbacks short and named when logic grows
  • Use map/filter/reduce when you need a result array
  • Use for...of when you need break or continue
  • Build new arrays in separate variables when needed

❌ Don’t

  • Assign forEach result expecting an array
  • Try to break out with break or return from outer scope
  • Mutate the array length during iteration carelessly
  • Replace map with forEach + push without reason
  • Use forEach for async sequential work (use for...of + await)

Key Takeaways

Knowledge Unlocked

Five things to remember about Array.forEach()

Iterate arrays cleanly for side-effect-driven workflows.

5
Core concepts
🔄 02

Side effects

Do something.

Purpose
03

undefined

No return.

Output
🚫 04

No break

Use for loop.

Limit
🌟 05

ES5

IE9+.

Support

❓ Frequently Asked Questions

forEach() runs a callback function once for every element in the array, in order. It is used for side effects like logging, updating DOM, or accumulating values in outer variables.
forEach() always returns undefined. It does not produce a new array. Use map(), filter(), or reduce() when you need a transformed result.
No. break and continue do not work inside forEach(). return only skips the rest of the current callback. Use for...of or a classic for loop if you need early exit.
map() returns a new array of transformed values. forEach() returns undefined and is meant for running code on each element without building a return value.
Yes. forEach() does not call the callback for holes (empty slots) in sparse arrays.
forEach() is ES5 (2009). It works in all modern browsers and has been supported in Internet Explorer 9+.
Did you know?

NodeList objects from document.querySelectorAll() also have a forEach method in modern browsers, so you can iterate DOM collections the same way as arrays—without converting to an array first.

Continue to includes()

Learn how to check whether an array contains a value with a simple boolean test.

includes() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful