📢
Admissions Open | Free Career Counselling | Limited Scholarships
Register Now →

Learning Guides

forEach Loop in JavaScript: Syntax, 8 Examples and 7 Traps We Tested

Learn the forEach loop in JavaScript with 8 examples, how to break or skip, why async/await fails (we timed it) and when to use map or for...of.

You wrote a forEach, added await inside it, and your code printed "done" before anything was done.

Or you tried break and got a SyntaxError.

The forEach loop in JavaScript looks simple, and it is. But it has a few rules that tutorials skip, and those rules cause real bugs in real projects.

In this guide, you'll learn the syntax, 8 examples you'll actually use, and what happens in 7 tricky situations. We ran every one in Node.js 22 and timed the async cases, so you get results instead of guesses.

Let's get started.

The forEach loop in JavaScript is an array method, array.forEach(callback), that runs a function once for every element, in order from index 0. It passes each element, its index and the whole array to your callback, always returns undefined, and cannot be stopped with break.

Use it for side effects such as logging, updating the page or saving data.

Quick answer: forEach loop in JavaScript (December 2026)

  • array.forEach((element, index, array) => { ... }) runs the callback once per element and always returns undefined.
  • A break statement inside forEach throws "SyntaxError: Illegal break statement", and return only skips the current item.
  • In our Node.js 22 test, forEach with await logged "done" after 0 ms, while for...of took 302 ms and Promise.all took 100 ms for three 100 ms calls.
  • Use map() when you need a new array, for...of when you need break or await, and some() or find() to stop early.
  • On 1,000,000 numbers, a classic for loop took 1.6 ms and forEach took 5.4 ms in our test; on 1,000 numbers both took under 0.03 ms.

Contents

  1. What Is the forEach Loop in JavaScript?
  2. JavaScript forEach Syntax and Parameters
  3. 8 forEach JavaScript Examples You'll Actually Use
  4. How to Break Out of a forEach Loop in JavaScript
  5. forEach With async/await: What Really Happens (We Timed It)
  6. 7 forEach Traps We Tested in Node.js 22
  7. forEach on Maps, Sets, NodeLists and Iterators
  8. forEach Loop in JavaScript vs map, for...of and for
  9. The 4-Question Loop Test: When to Use forEach
  10. FAQ
forEach loop in JavaScript: 7 traps tested in Node.js 22
One callback, once per element, in order.

What Is the forEach Loop in JavaScript?

The forEach loop in JavaScript is a built-in method on arrays that calls a function you provide for each element, from the first index to the last. Technically it's a method (Array.prototype.forEach()), so the precise name is the Array forEach JavaScript method, not a loop statement like for or while. Almost everyone still calls it the forEach loop.

forEach arrived with ECMAScript 5 in 2009, according to W3Schools' forEach reference. MDN lists it as widely available in every browser since July 2015 (MDN).

Here's the smallest useful example:

const subjects = ["Maths", "Physics", "Chemistry"];

subjects.forEach((subject) => {
  console.log(subject);
});
// Maths
// Physics
// Chemistry

Compare it with the classic for loop doing the same job:

for (let i = 0; i < subjects.length; i++) {
  console.log(subjects[i]);
}

Same output. But forEach has no counter to manage, no i < length to get wrong, and no off-by-one bugs.

forEach loop in JavaScript visiting each array element with a callback function
The callback visits every element in order, with its index.

That's why forEach is often the first array method people learn after the basic loops. If you're coming from Python, it plays a similar role to for item in list from our guide to loops in Python, with one big difference: you can't break out of it.

JavaScript forEach Syntax and Parameters

The JavaScript forEach method takes one required argument, a callback function, and one optional argument, thisArg. The callback receives up to three values every time it runs.

array.forEach(function callback(element, index, array) {
  // your code
}, thisArg);
Parameter Required? What it holds Example value
element Yes The current item "Physics"
index No Position of the current item 1
array No The full array forEach was called on ["Maths", "Physics", "Chemistry"]
thisArg No The value of this inside a regular function callback an object
Return value n/a Always undefined undefined
JavaScript forEach syntax with element, index, array and thisArg parameters labelled
Three callback parameters, one optional thisArg, zero return value.

Two details matter more than the table suggests.

First, the return value of your callback is thrown away. MDN says the callback's return value is discarded and forEach itself returns undefined (MDN). So you can't chain it: in our test, [1, 2].forEach(x => x).map(x => x) threw "Cannot read properties of undefined (reading 'map')".

Second, thisArg only works with regular functions. Arrow functions take this from the surrounding code, so MDN notes you can skip thisArg when you pass an arrow function. In modern code, you'll rarely need it.

8 forEach JavaScript Examples You'll Actually Use

The forEach JavaScript examples below cover the jobs forEach does best: totals, updates, logging, numbering and working with objects and web pages. Each one is a side effect, which is exactly what forEach is built for.

1. Add Up Student Marks

const marks = [78, 85, 91, 66, 88];
let total = 0;

marks.forEach((mark) => {
  total += mark;
});

console.log(total); // 408
console.log(total / marks.length); // 81.6

2. Calculate a Cart Total in Rupees With GST

const cart = [
  { item: "Python book", price: 450, qty: 2 },
  { item: "USB keyboard", price: 799, qty: 1 },
];
let subtotal = 0;

cart.forEach(({ price, qty }) => {
  subtotal += price * qty;
});

const gst = subtotal * 0.18;
console.log(`Total: ₹${(subtotal + gst).toFixed(2)}`); // Total: ₹2004.82

Destructuring { price, qty } right in the parameter keeps the callback short. The 18% rate here is just sample data for the example.

3. Number a List Using the Index

const toppers = ["Asha", "Rohit", "Sneha"];

toppers.forEach((name, index) => {
  console.log(`${index + 1}. ${name}`);
});
// 1. Asha
// 2. Rohit
// 3. Sneha

4. Update Objects in Place

const students = [
  { name: "Asha", fee: 15000, paid: true },
  { name: "Rohit", fee: 15000, paid: false },
];

students.forEach((student) => {
  student.status = student.paid ? "Clear" : "Send reminder";
});

This works because each student is a reference to the same object in the array. Reassigning a plain number doesn't work the same way (see trap #4 below).

5. Loop Over an Object With Object.entries

Plain objects don't have forEach. Convert them first with Object.entries():

const scores = { maths: 91, science: 84, english: 77 };

Object.entries(scores).forEach(([subject, score]) => {
  console.log(`${subject}: ${score}`);
});

Use Object.keys() or Object.values() the same way when you only need one side.

6. Update Every Button on a Web Page

document.querySelectorAll(".enquiry-btn").forEach((btn) => {
  btn.addEventListener("click", () => {
    btn.textContent = "Request sent";
  });
});

querySelectorAll() returns a NodeList, which has its own forEach. More on that in the Maps and NodeLists section.

7. Build a Lookup Object

const courses = [
  { id: "ds", name: "Data Science" },
  { id: "mern", name: "Full Stack MERN" },
];
const byId = {};

courses.forEach((course) => {
  byId[course.id] = course.name;
});
// { ds: "Data Science", mern: "Full Stack MERN" }

8. Log a Simple Report

const leads = [
  { city: "Nagpur", count: 42 },
  { city: "Pune", count: 31 },
];

leads.forEach(({ city, count }) => console.log(`${city}: ${count} enquiries`));
Eight forEach JavaScript examples including totals, cart GST, object updates and DOM buttons
Every example is a side effect. That's forEach's job.

Notice what's missing from this list: creating a new array of transformed values. That's map()'s job, and using forEach plus push() for it is the most common style mistake reviewers flag.

How to Break Out of a forEach Loop in JavaScript

You cannot break out of a forEach loop in JavaScript. MDN states there is no way to stop or break a forEach() loop other than by throwing an exception (MDN). Here's what each option actually does, from our Node.js 22 test:

What you write inside forEach What happens
break; SyntaxError: Illegal break statement (code won't even run)
continue; SyntaxError (same reason: you're inside a function, not a loop)
return; Skips only the current item, then carries on (works like continue)
throw new Error() Stops the loop, but you need try/catch around it, and it's ugly

So return is your "continue":

[1, 2, 3, 4].forEach((n) => {
  if (n === 2) return; // skip 2
  console.log(n);
});
// 1, 3, 4

And when you genuinely need to stop early, use a different tool:

// Stop at the first failing mark: some() stops when the callback returns true
const marks = [78, 85, 31, 66];
const hasFail = marks.some((m) => m < 35); // checks 3 items, not 4

// Find the first match
const firstFail = marks.find((m) => m < 35); // 31

// Need a real break? Use for...of
for (const m of marks) {
  if (m < 35) break;
  console.log(m);
}

In our test, some() on [1, 2, 3, 4, 5] ran the callback only twice when the match was the second item. forEach would have run it five times, every time.

How to break forEach in JavaScript using some, find or for...of instead
forEach can skip an item. It can't stop.

forEach With async/await: What Really Happens (We Timed It)

forEach does not wait for await. MDN explains that forEach expects a synchronous function and does not wait for promises (MDN). Each async callback starts, hits await, hands back a promise that forEach ignores, and forEach moves straight on.

To show how much this matters, we simulated three API calls (for example, fetching three students' marks) that each take 100 ms, and ran them three ways in Node.js 22 on 4 December 2026:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const fetchMarks = async (id) => { await wait(100); return id * 10; };
const ids = [1, 2, 3];

// A: forEach (broken)
const a = [];
ids.forEach(async (id) => a.push(await fetchMarks(id)));
console.log(a); // [] at 0 ms

// B: for...of (one after another)
const b = [];
for (const id of ids) b.push(await fetchMarks(id));

// C: Promise.all + map (all at once)
const c = await Promise.all(ids.map(fetchMarks));

Here's what happened:

Pattern Time until the next line ran Results at that moment Order kept?
forEach(async ...) 0 ms [] (empty) No: with different delays, results arrived as [2, 3, 1]
for...of + await 302 ms [10, 20, 30] Yes
await Promise.all(ids.map(...)) 100 ms [10, 20, 30] Yes
forEach async await timing compared with for...of and Promise.all in Node.js 22
forEach doesn't wait. for...of waits for each. Promise.all waits for all.

The worst part wasn't the timing. Errors escape.

We wrapped an async forEach in try/catch and threw an error inside the callback. The catch block never ran, the rejection went unhandled, and Node.js 22 crashed the whole process with exit code 1.

In an Express API, that's the difference between a clean 500 error and a server that restarts.

So the rule is simple:

  • Need the calls in order (each depends on the last, or the API has rate limits)? Use for...of with await.
  • Calls are independent? Use await Promise.all(items.map(fn)). In our test it was 3x faster than for...of.
  • Some calls may fail and you still want the rest? Use Promise.allSettled().

Important: await items.forEach(...) does nothing useful. forEach returns undefined, so you're awaiting undefined, and the code below still runs before your work is done.

If you're building APIs, this exact bug shows up in MERN projects that save a list of items to MongoDB. It's one of the habits worth fixing before you start the MERN stack project ideas in our portfolio guide.

7 forEach Traps We Tested in Node.js 22

Seven forEach behaviours surprise beginners and still catch experienced developers. We ran each one in Node.js 22.23.5 so you can see the exact result, not a "should".

# Trap Code What actually happens
1 Expecting a return value const r = [1,2,3].forEach(x => x*2) r is undefined
2 Empty slots in a sparse array [1, , 3].forEach(...) Index 1 is skipped entirely; [1, undefined, 3] visits all three
3 Adding items during the loop arr.push() inside forEach on 3 items Callback runs 3 times; the new items are not visited
4 Reassigning the element v = v * 2 Original array unchanged; use arr[i] = v * 2 via the third parameter
5 Removing items during the loop arr.shift() when visiting "b" in a, b, c, d Visited a, b, d. Item "c" was silently skipped
6 Calling it on an object or string ({}).forEach, "abc".forEach TypeError: .forEach is not a function
7 Forgetting the callback [1].forEach() TypeError: undefined is not a function
Seven forEach JavaScript traps tested in Node.js 22 with actual results
Trap #5 is the dangerous one. No error, just a missing item.

Trap #5 deserves a second look.

forEach decides how far to go based on the array's length at the start, and it reads each index as it reaches it. When you remove an item, everything after it shifts left by one, so the loop jumps over the next element.

No error, no warning. Just wrong data.

The fix: never add or remove items in the array you're looping over. Build a new array with filter() instead:

const active = students.filter((s) => s.paid);

For trap #2, MDN confirms the callback is not invoked for empty slots in sparse arrays (MDN). Sparse arrays are rare in real code, but they appear when you set arr[10] = x on a short array or use new Array(5).

forEach on Maps, Sets, NodeLists and Iterators

forEach isn't only an array method. Map, Set, NodeList and (since 2025) iterators have their own forEach, and each one has a small difference worth knowing.

Map: the callback gets (value, key, map), with the value first. MDN confirms this order and that entries are visited in insertion order (MDN Map.forEach).

const fees = new Map([["Asha", 15000], ["Rohit", 12000]]);
fees.forEach((amount, name) => console.log(name, amount));

Set: sets have no keys, so the callback receives the value twice. In our test, new Set(["x"]).forEach((v, k) => ...) gave v = "x" and k = "x".

NodeList: the list returned by document.querySelectorAll() has forEach, widely available since October 2017 per MDN's NodeList.forEach page.

HTMLCollection: the list from getElementsByClassName() does not have forEach. Our jsdom test returned undefined. Convert it first:

Array.from(document.getElementsByClassName("card")).forEach((card) => {
  card.classList.add("visible");
});

Iterators: Iterator.prototype.forEach() became Baseline newly available in March 2025 as part of iterator helpers (web.dev). It lets you call forEach on generators and on .values() or .entries() without converting to an array first:

function* rollNumbers() { yield 101; yield 102; }
rollNumbers().forEach((roll) => console.log(roll)); // 101, 102

MDN notes that unlike most iterator helpers, this forEach is not lazy, so it never finishes on an infinite iterator (MDN Iterator.forEach).

forEach callback parameters for Array, Map, Set and NodeList, and HTMLCollection without forEach
Map puts the value first. HTMLCollection has no forEach at all.

forEach Loop in JavaScript vs map, for...of and for

The difference between forEach and the other loops comes down to three things: whether you need a result, whether you need to stop early, and whether you need await. Here's the full map vs forEach JavaScript comparison, plus for...of and the classic for loop:

forEach map() for...of for (let i...)
Returns undefined A new array Nothing (statement) Nothing (statement)
break / continue No No Yes Yes
Works with await No Yes, with Promise.all Yes Yes
Chainable No Yes (.filter().map()) No No
Gives index Yes Yes With .entries() Yes
Works on Map, Set, strings Map and Set only No (arrays only) Yes, any iterable Arrays and strings
Best for Side effects Transforming data Async work, early exit Speed, custom steps
Map vs forEach JavaScript comparison with for...of and the classic for loop
Pick by the job, not by habit.

Is forEach Slower Than a for Loop?

Yes, forEach is slower than a classic for loop on very large arrays, but the gap doesn't matter for typical web data. We summed arrays of three sizes in Node.js 22 (median of 30 runs after 10 warm-ups, 4 December 2026):

Array size for (let i) for...of forEach reduce
1,000 0.009 ms 0.027 ms 0.008 ms 0.007 ms
100,000 0.078 ms 0.905 ms 0.526 ms 0.508 ms
1,000,000 1.6 ms 8.1 ms 5.4 ms 4.9 ms
forEach vs for loop benchmark in Node.js 22 at one million items
3x slower at a million items. Invisible at a thousand.

Two honest notes on these numbers.

At 1 million items, the for loop was about 3x faster than forEach. At 1,000 items (a page of products, a class list, an API response), every method finished in under 0.03 ms. You'd never notice.

And for...of came last in our run, while the LeanyLabs benchmark on Node 22.3 found for and for...of roughly equal. Micro-benchmarks shift between engine versions and machines. Write readable code first, and switch to a for loop only when profiling shows a real hot path.

The 4-Question Loop Test: When to Use forEach

The 4-Question Loop Test is a quick way to pick the right loop. Ask these questions in order, and stop at the first "yes":

  1. Do I need a new array or a single value back? Use map(), filter() or reduce().
  2. Do I need to stop early? Use some(), find(), every() or for...of with break.
  3. Is there an await inside? Use for...of (in order) or Promise.all() with map() (in parallel).
  4. Is this a hot path with hundreds of thousands of items? Use a classic for loop.

All four answers "no"? Use forEach.

That covers most everyday jobs: logging, updating the DOM, adding up totals, sending items to another function.

The 4-Question Loop Test flowchart for choosing forEach, map, for...of or a for loop
Four no's means forEach is the right call.

Want to see how loops like these fit into a full-stack job? Read what a MERN stack developer does, and practise explaining forEach vs map out loud with our MERN interview questions. It's one of the most common JavaScript screening questions.

Now It's Your Turn

The forEach loop in JavaScript is the right tool for one job: running a side effect for every element. It always returns undefined, it can't break, and it won't wait for await.

When you need a result, reach for map(). When you need to stop or wait, reach for for...of. When you're unsure, run the 4-Question Loop Test.

Which trap surprised you most?

If you'd like trainers to review your JavaScript and guide you through real MERN projects, Fireblaze's AI-Powered Full Stack Development course runs in classroom batches at Mate Square, Nandanvan and Sadar in Nagpur, or live online.

Not sure it's for you yet? Book a free career counselling session. Disclosure: Fireblaze AI School publishes this guide.

FAQ

What is the forEach loop in JavaScript used for?

The forEach loop in JavaScript is used to run a function once for every element of an array, usually for side effects such as logging values, updating the page, adding up totals or saving data. It always returns undefined, so use map() instead when you need a new array.

Can you break out of a forEach loop?

No, you cannot break out of a forEach loop. A break statement inside the callback causes a SyntaxError, and return only skips the current element. To stop early, use some(), find(), every() or a for...of loop with break.

Does forEach work with async/await?

No, forEach does not wait for async callbacks. In our Node.js 22 test, code after an async forEach ran after 0 ms with empty results, and an error thrown inside it escaped try/catch. Use for...of with await for sequential calls, or await Promise.all() with map() for parallel calls.

What is the difference between map and forEach in JavaScript?

The difference is the return value: map() returns a new array built from your callback's return values, while forEach returns undefined. Use map() to transform data and chain more methods, and use forEach when you only need to do something with each element.

Does forEach change the original array?

forEach does not change the original array by itself, but your callback can. Reassigning the element parameter has no effect, while writing to array[index] or changing an object's properties inside the callback does modify the original data.

Can I use forEach on an object in JavaScript?

Plain objects do not have a forEach method, so calling it throws a TypeError. Convert the object first with Object.entries(), Object.keys() or Object.values(), then call forEach on the resulting array.

Sources

  1. MDN: Array.prototype.forEach(), 2026
  2. MDN: Map.prototype.forEach(), 2026
  3. MDN: NodeList.forEach(), 2026
  4. MDN: Iterator.prototype.forEach(), 2026
  5. web.dev: Iterator helpers have become Baseline Newly available, May 2025
  6. W3Schools: JavaScript Array forEach(), 2026
  7. LeanyLabs: JS array performance benchmark, 2024
  8. Fireblaze AI School forEach loop in JavaScript tests: behaviour, async timing, DOM (jsdom 31.0.1) and benchmark scripts on Node.js 22.23.5, run 4 December 2026