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
array.forEach((element, index, array) => {
// action on the element
});Callback parameters:
| Argument | Description |
|---|---|
element | The current array element |
index | The index of the current element |
array | The original array itself |
Example 1. Logging elements to the console
const numbers = [1, 2, 3];
numbers.forEach(num => {
console.log(num);
});
// Outputs:
// 1
// 2
// 3The method simply runs through each element, returning nothing.
Example 2. Modifying external data
const users = ['Tim', 'Alex', 'John'];
const greetings = [];
users.forEach(name => {
greetings.push(`Hello, ${name}!`);
});
console.log(greetings);
// ['Hello, Tim!', 'Hello, Alex!', 'Hello, John!']Here
forEachis used to fill a new array manually (unlikemap, which does this automatically).
Example 3. Working with indices
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(`${index + 1}. ${fruit}`);
});
// 1. apple
// 2. banana
// 3. cherryCommon mistakes and limitations
- Does not return a new array
const result = [1, 2, 3].forEach(n => n * 2);
console.log(result); // undefinedUse map() if you need to get a new array.
2. You cannot break the loop (break or return)
[1, 2, 3].forEach(num => {
if (num === 2) return; // will not stop the loop
console.log(num);
});
// Outputs: 1, 3If you need to break the loop, use a regular for or for...of.
3. Does not work with async/await as expected
await array.forEach(async item => {
await fetch(item); // will not wait for all requests
});For asynchronous operations it's better to use:
for (const item of array) {
await fetch(item);
}When to use forEach()
| Goal | Does forEach() fit |
|---|---|
| Perform an action for each element | Yes |
| Transform the array | No - use map() |
| Filter elements | No - use filter() |
| Find an element | No - use find() |
| Break the loop | No - 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()
| Method | Returns a new array | Mutates the original | Can be broken | Main purpose |
|---|---|---|---|---|
| forEach() | No | No | No | Just iterate |
| map() | Yes | No | No | Transform data |
| filter() | Yes | No | No | Filter elements |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.