Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript forEach()

forEach runs a callback for each element in the array.

It is best for side effects, not for building new arrays.

Why We Need It

Some tasks are about doing something for each item, like logging or updating totals.

forEach expresses that intent clearly.

Syntax

array.forEach((value, index, array) => { ... })

Basic Example

1. Basic forEach

const nums = [1, 2, 3];
nums.forEach((n) => console.log(n));

Run a callback for each item.

Real World Example

2. Using index

const items = ["a", "b"];
items.forEach((item, i) => console.log(i, item));

Access index and value.

Multiple Use Cases

Side Effects

forEach runs a callback for every element.

It is best when you need side effects like logging or updating external state.

No Return

forEach always returns undefined.

If you need a new array, use map instead.

Cannot Break

You cannot break out of forEach early.

Use a for...of loop when you need break or continue.

More Examples

3. Update external state

const nums = [1, 2, 3];
let total = 0;
nums.forEach((n) => {
  total += n;
});

console.log(total);

Use forEach for side effects.

4. No early exit

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

return only skips the current callback.

Comparison

Without

const out = [];
for (const n of nums) {
  out.push(n * 2);
}

With

const out = nums.map((n) => n * 2);

Common Mistakes and Fixes

Using forEach to build arrays

Use map or filter to return new arrays.

Trying to break

Use for...of if you need break or continue.

Expecting a return value

forEach always returns undefined.

Interview Questions

Does forEach return anything?

No, it returns undefined.

Can you break out of forEach?

No, use a loop instead.

When is forEach appropriate?

When you need side effects, not transformations.

Practice Problem

Practice: Log each item with its index using forEach.

const items = ["x", "y", "z"];
// TODO: log index and value

One Possible Solution

const items = ["x", "y", "z"];
items.forEach((item, i) => console.log(i, item));

Frequently Asked Questions

Does forEach return a new array?

No, it returns undefined.

Can I break out of forEach?

No, use a loop if you need early exit.

When should I use forEach?

For side effects like logging or updating external state.

Try It Yourself

Try changing the array items and see the output.