Array.forEach()
Runs a function for each element (no returned array result).
array.forEach(callbackFn, thisArg?)This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Runs a function for each element (no returned array result).
Array.prototype.forEach() executes a provided callbackFn once for each array element in ascending order. It is specifically designed for side effects, such as logging, mutating external variables, or updating the DOM. Unlike methods like map() or reduce(), it always returns undefined, which means it cannot be chained with other array methods. Regarding performance, forEach() is generally slower than a traditional for-loop or for...of loop due to the overhead of per-iteration function calls. An important edge case is that forEach() skips empty slots in sparse arrays (holes). Furthermore, forEach() is synchronous and does not wait for promises; if the callbackFn is an async function, the loop will proceed without waiting for the promise to resolve. Crucially, there is no way to stop or break a forEach() loop other than by throwing an exception; for early termination, use methods like every(), some(), or find(). The syntax is array.forEach(callbackFn, thisArg?).
Quick reference
Syntax
array.forEach(callbackFn, thisArg?)
Inputs
Parameters
See it in practice
Examples
Basic Iteration and Side Effects
let total = 0;
const prices = [10.99, 5.50, 2.00];
prices.forEach(function(price) {
total += price;
});
console.log('Total:', total.toFixed(2));Total: 18.49
Uses forEach to iterate through an array and update an external variable to calculate a sum.
Using Index and Array Arguments
const items = ['Alpha', 'Beta', 'Gamma'];
items.forEach((item, index, arr) => {
console.log('Processing ' + (index + 1) + ' of ' + arr.length + ': ' + item);
});Processing 1 of 3: Alpha Processing 2 of 3: Beta Processing 3 of 3: Gamma
Demonstrates accessing the optional index and the original array parameters within the callback.
Modifying Objects in an Array
const tasks = [{ id: 1, done: false }, { id: 2, done: false }];
tasks.forEach(task => {
task.done = true;
});
console.log(tasks[0].done);true
Shows how forEach can be used to mutate the properties of objects contained within an array.
Debug faster
Common Errors
LogicError
Cause: Attempting to use the 'break' or 'continue' keywords inside the callback function.
Fix: forEach does not support breaking. Use a standard 'for' loop, 'for...of', or methods like 'some()' or 'every()' which allow for early exit.
const arr = [1, 2, 3];
arr.forEach(n => {
if (n === 2) break; // SyntaxError: Illegal break statement
});TypeError
Cause: Attempting to chain array methods after forEach().
Fix: Since forEach returns undefined, use map() if you need to transform the data and then filter or sort it.
const values = [1, 2, 3];
const result = values.forEach(x => x * 2).filter(x => x > 2); // TypeError: Cannot read property 'filter' of undefinedLogicError
Cause: Expecting forEach to await asynchronous operations.
Fix: forEach is not promise-aware. Use a 'for...of' loop with 'await' or use 'Promise.all()' with 'map()'.
const urls = ['/api/1', '/api/2'];
urls.forEach(async (url) => {
const data = await fetch(url);
console.log('Fetched');
});
console.log('Finished'); // This will likely log BEFORE 'Fetched'Runtime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Runs a function for each element (no returned array result).
callback: Executed for each element. thisArg: Value used as 'this' inside callback.
LogicError: forEach does not support breaking. Use a standard 'for' loop, 'for...of', or methods like 'some()' or 'every()' which allow for early exit. TypeError: Since forEach returns undefined, use map() if you need to transform the data and then filter or sort it. LogicError: forEach is not promise-aware. Use a 'for...of' loop with 'await' or use 'Promise.all()' with 'map()'.