Master Code
On The Go

Learn. Practice. Build.

Home › Code Snippets › JavaScript › Reference › forEach()

JavaScript Reference

Array.prototype.forEach()

Executes a callback for each element. Returns undefined. The go-to method for side effects.

Last updated: October 2026

forEach() runs a function on every element for its side effects. Use it to log, save, or update — not to build a new array.

Full definition: Array.prototype.forEach() executes a provided function once for each array element. It returns undefined and cannot be chained.

🎬 Live Example

Click any button to see forEach in action.

Input:

                
Result:

            

💡 Note that forEach always returns undefined, no matter what the callback does.

📝

Basic Syntax

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

// Always returns undefined

If you need the return value, use map. If you need to break out early, use for...of.

🎯 Syntax & Parameters

Parameter Type Description
callbackFunctionCalled once per element.
elementanyThe current element.
indexnumberThe index of the current element.
arrayArrayThe original array.
1

Logging Each Item

const names = ['Alice', 'Bob', 'Carol'];

names.forEach(name => {
    console.log(name);
});
// Alice
// Bob
// Carol

The classic side effect. forEach is designed for exactly this.

2

Accumulating Values

const numbers = [10, 20, 30, 40];

// Note: reduce is the better tool for this
let total = 0;
numbers.forEach(n => {
    total += n;
});
console.log(total); // 100

💡 Better alternative: Use reduce for sums. Reserve forEach for side effects that aren't about accumulating a value.

3

Updating the DOM

const links = ['Home', 'About', 'Contact'];
const nav = document.querySelector('nav');

links.forEach(link => {
    const a = document.createElement('a');
    a.href = `/${link.toLowerCase()}`;
    a.textContent = link;
    nav.appendChild(a);
});

This is where forEach shines — you don't need a return value, you just want to do something to each element.

4

Using the Index Argument

const letters = ['a', 'b', 'c'];

letters.forEach((letter, i) => {
    console.log(`${i}: ${letter}`);
});
// 0: a
// 1: b
// 2: c
5

Iterating Over Objects (using Object.keys)

const user = { name: 'Alice', age: 30, city: 'Karachi' };

// Object.keys
Object.keys(user).forEach(key => {
    console.log(`${key}: ${user[key]}`);
});

// Object.values
Object.values(user).forEach(value => {
    console.log(value);
});

// Object.entries — gives both key and value
Object.entries(user).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

forEach is an Array method. To iterate over object keys, convert to an array first.

🎯 forEach vs map vs for...of

Feature forEach map for...of
Return valueundefinedNew array—
Can break earlyNoNoYes
Can awaitNoNoYes
Best forSide effectsTransformationComplex logic, early exit

⚠️ Common Mistakes

❓ Frequently Asked Questions

What does Array.forEach() do in JavaScript?

Array.forEach() executes a provided callback function once for each element of the array. It returns undefined and is used for side effects like logging, updating DOM, or mutating external state.

What is the difference between forEach and map?

map returns a new array of transformed values. forEach returns undefined and is only useful for side effects. Use map when you need the result, forEach when you just need to do something for each element.

Can I break out of a forEach loop?

No. forEach cannot be broken out of with break or continue. If you need early exit, use a for...of loop or Array.prototype.some() instead.

Can I use async/await inside forEach?

Not directly. forEach does not await async callbacks — it fires them all in parallel and returns immediately. Use for...of with await or Promise.all with map.

Does forEach modify the original array?

forEach doesn't change the array it iterates over, but the callback can mutate elements. Mutating elements inside forEach is generally discouraged.

🎯 What's Next?

← All JavaScript Reference