Last modified: Jul 31, 2026
JavaScript forEach() Array Method Explained
The forEach() method is a built-in JavaScript function. It helps you loop through array elements. It is clean, readable, and perfect for beginners.
Unlike a traditional for loop, forEach() is more expressive. You write less code. It also keeps your intent clear. You want to do something for each item.
This guide will explain everything. We will cover syntax, parameters, examples, and common mistakes. By the end, you will use forEach() with confidence.
What is forEach()?
forEach() executes a function once for each element in the array. It does not return a new array. It simply performs an action on each item.
Think of it as a task manager. You give it a list of tasks. It goes through each one and completes them.
This method is part of the JavaScript Array Methods Guide family. It is one of the most used methods for iteration.
Syntax of forEach()
The basic syntax is simple. You call it on an array. You pass a callback function inside.
array.forEach(function(currentValue, index, array) {
// Your code here
});
Let's break down the parameters. The callback function can take three arguments.
currentValue is required. It holds the current element's value. index is optional. It gives you the position number. array is also optional. It refers to the original array.
In most cases, you only need currentValue. It is the most common usage.
Basic Example
Let's start with a simple example. We have an array of numbers. We want to print each one.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
When you run this code, you will see each number printed on a new line.
1
2
3
4
5
Notice how clean this is. No need to set a counter or check a condition. forEach() handles all that for you.
Using Index in forEach()
Sometimes you need to know the position of an item. The index parameter helps with that.
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(function(fruit, index) {
console.log(index + ': ' + fruit);
});
This will output the index and the fruit name.
0: apple
1: banana
2: cherry
Remember, arrays are zero-indexed. So the first item has an index of 0.
Arrow Function with forEach()
Modern JavaScript uses arrow functions. They make the code even shorter. This is the preferred style today.
const colors = ['red', 'green', 'blue'];
colors.forEach(color => console.log(color));
This does the exact same thing as the function version. It is just more concise. Arrow functions are great for simple operations.
You can also use them with multiple parameters. Just wrap them in parentheses.
colors.forEach((color, index) => {
console.log(`Color at index ${index} is ${color}`);
});
Modifying Array Elements
Can you change the array inside forEach()? Yes, you can. But you need to be careful.
If you modify the original array, it will affect the iteration. Here is an example of doubling values.
let scores = [10, 20, 30];
scores.forEach((score, index) => {
scores[index] = score * 2;
});
console.log(scores);
After running, the array is updated.
[20, 40, 60]
Notice we used the index to assign the new value. This works because we are referencing the original array directly.
Working with Objects
Arrays often contain objects. forEach() is perfect for iterating over them. Let's see an example.
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
users.forEach(user => {
console.log(`${user.name} is ${user.age} years old.`);
});
This prints a friendly message for each user.
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
This is a very common pattern. You will use it often. For more complex object handling, check out this JavaScript Array of Objects Guide.
forEach() vs for Loop
Many beginners wonder which one to use. Let's compare them.
A for loop gives you more control. You can break out of it. You can skip iterations with continue. forEach() does not support these.
However, forEach() is easier to read. It reduces boilerplate code. For simple tasks, it is the better choice.
Here is a side-by-side comparison.
// Traditional for loop
const arr = ['a', 'b', 'c'];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// forEach method
arr.forEach(item => console.log(item));
Both produce the same output. But the forEach() version is shorter and clearer.
Important Limitations
There are some things you should know. forEach() cannot be stopped early. There is no break statement.
If you need to stop, use a for loop or some() method. Also, forEach() does not work with await inside the loop. It will not wait for promises.
For asynchronous operations, consider using for...of or Promise.all. This is a common pitfall for developers.
Another limitation is that forEach() skips empty slots in sparse arrays. This can be confusing. But it is rarely an issue in practice.
Performance Considerations
Is forEach() slower than a for loop? Yes, it can be slightly slower. But the difference is negligible for most applications.
Modern JavaScript engines optimize forEach() very well. You should prioritize readability over micro-optimizations. Clean code is more important.
If you are working with millions of items, you might notice a difference. In that case, test both and measure. Otherwise, use forEach() for clarity.
Real-World Use Cases
Let's look at some practical examples. You will see forEach() in many codebases.
One common use case is updating the DOM. You can iterate over data and create elements.
const items = ['Task 1', 'Task 2', 'Task 3'];
const list = document.getElementById('myList');
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
list.appendChild(li);
});
Another use case is logging data for debugging. It is great for quick checks.
const data = [10, 20, 30];
data.forEach(value => console.log(`Value: ${value}`));
You can also accumulate results. But for that, you might prefer reduce(). See our JavaScript Array reduce() Explained guide for more.
Common Mistakes to Avoid
Beginners often make a few mistakes. Let's highlight them.
First, forgetting to use return. forEach() ignores return values. It always returns undefined. Do not try to collect results from it.
Second, modifying the array length. This can cause unexpected behavior. It is safer to avoid changing the array structure during iteration.
Third, using forEach() on non-arrays. It only works on arrays. For array-like objects, convert them first using Array.from().
Here is an example of a common error.
const result = [1, 2, 3].forEach(num => num * 2);
console.log(result); // undefined
If you need a new array, use map() instead. forEach() is for side effects, not for creating new arrays.
Converting Array to String
Sometimes you need to convert an array to a string. forEach() can help with that manually.
const words = ['Hello', 'World'];
let sentence = '';
words.forEach((word, index) => {
sentence += word;
if (index < words.length - 1) {
sentence += ' ';
}
});
console.log(sentence);
This builds a string with a space between words.
Hello World
However, there is a simpler built-in method. Check out this JavaScript Array to String guide for a better way.
Destructuring with forEach()
You can combine forEach() with destructuring. This is very powerful for arrays of arrays.
const pairs = [[1, 'one'], [2, 'two'], [3, 'three']];
pairs.forEach(([number, word]) => {
console.log(`${number} is spelled as ${word}`);
});
This prints a nice message for each pair.
1 is spelled as one
2 is spelled as two
3 is spelled as three
Destructuring makes the code more readable. For a deeper dive, see our JavaScript Array Destructuring Guide.
Nested forEach() Loops
You can nest forEach() loops. This is useful for multi-dimensional arrays.
const matrix = [
[1, 2],
[3, 4]
];
matrix.forEach(row => {
row.forEach(cell => {
console.log(cell);
});
});
This prints all numbers in order.
1
2
3
4
Be careful with nested loops. They can be slow for large datasets. But for small ones, they are perfectly fine.
Checking Array Length
Sometimes you want to run a loop only if the array has items. You can check the length first.
const emptyArray = [];
if (emptyArray.length > 0) {
emptyArray.forEach(item => console.log(item));
} else {
console.log('Array is empty');
}
This prevents unnecessary iteration. It is a good practice. For more on this topic, visit our JavaScript Array Length Guide.
Conclusion
forEach() is a fundamental method in JavaScript. It makes array iteration simple and readable. You learned the syntax, parameters, and examples.
We covered arrow functions, modifying arrays, and working with objects. We also discussed limitations and performance. Now you know when to use it and when to avoid it.
Remember, forEach() is for side effects. Use map() for transformations. Use filter() for selecting items. Use reduce() for accumulation.
Practice with your own examples. The more you use it, the more natural it becomes. Happy coding!