Skip to main content

forEach in an array

The forEach() method in JavaScript is used to iterate over array elements and perform an action on each element. Unlike map() and filter(), it returns nothing - it is used only for side effects (logging, a request, modifying data, and so on).


Syntax

javascript
array.forEach((element, index, array) => { // action on the element });

Callback parameters:

ArgumentDescription
elementThe current array element
indexThe index of the current element
arrayThe original array itself

Example 1. Logging elements to the console

javascript
const numbers = [1, 2, 3]; numbers.forEach(num => { console.log(num); }); // Outputs: // 1 // 2 // 3

The method simply runs through each element, returning nothing.


Example 2. Modifying external data

javascript
const users = ['Tim', 'Alex', 'John']; const greetings = []; users.forEach(name => { greetings.push(`Hello, ${name}!`); }); console.log(greetings); // ['Hello, Tim!', 'Hello, Alex!', 'Hello, John!']

Here forEach is used to fill a new array manually (unlike map, which does this automatically).


Example 3. Working with indices

javascript
const fruits = ['apple', 'banana', 'cherry']; fruits.forEach((fruit, index) => { console.log(`${index + 1}. ${fruit}`); }); // 1. apple // 2. banana // 3. cherry

Common mistakes and limitations

  1. Does not return a new array
javascript
const result = [1, 2, 3].forEach(n => n * 2); console.log(result); // undefined

Use map() if you need to get a new array. 2. You cannot break the loop (break or return)

javascript
[1, 2, 3].forEach(num => { if (num === 2) return; // will not stop the loop console.log(num); }); // Outputs: 1, 3

If you need to break the loop, use a regular for or for...of. 3. Does not work with async/await as expected

javascript
await array.forEach(async item => { await fetch(item); // will not wait for all requests });

For asynchronous operations it's better to use:

javascript
for (const item of array) { await fetch(item); }

When to use forEach()

GoalDoes forEach() fit
Perform an action for each elementYes
Transform the arrayNo - use map()
Filter elementsNo - use filter()
Find an elementNo - use find()
Break the loopNo - use for

Short version:

forEach() - performs an action for each element, returning nothing.

Memory formula: arr.forEach(action) -> returns nothing.


Comparison with map() and filter()

MethodReturns a new arrayMutates the originalCan be brokenMain purpose
forEach()NoNoNoJust iterate
map()YesNoNoTransform data
filter()YesNoNoFilter elements

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.