Concept of the forEach()
Function
The forEach()
function is used to loop through an array and process each element with a callback function. It applies the given callback to each array element in order, executing it once per element.
Using forEach()
allows you to handle array elements easily with a callback function, without needing to manually write a loop to access each item.
const arr = ["a", "b", "c"];
arr.forEach(function(element) {
console.log(element);
});
// Output:
// "a"
// "b"
// "c"
In the callback function, you can access not only the element's value but also its index and the entire array. This lets you perform various operations, such as printing each element or executing specific actions.
There are multiple ways to iterate over arrays, but the forEach()
function is one of the most widely used methods along with map()
.
See the section on forEach()
vs. map()
for more details.
Next, let's take a closer look at the syntax of the forEach()
function.
Syntax
arr.forEach(function(currentValue[, index[, array]]) {
// code to execute
}[, thisArg]);
arr
is the array that the forEach()
function is called on.
Parameters
The forEach()
function takes two parameters:
function (required) |
The callback function applied to each element of the array arr .
It accepts up to three arguments:
|
---|---|
thisArg (optional) |
An object to use as this when executing the callback function.
This parameter is optional and rarely needed. |
Callback Function Syntax
Here are the common ways to write the callback function for forEach()
:
// Arrow function with only current value:
forEach((element) => { /* … */ })
// Arrow function with current value and index:
forEach((element[, index]) => { /* … */ })
// Arrow function with current value, index, and original array:
forEach((element[, index[, array]]) => { /* … */ })
// Using a named callback function:
forEach(callbackFn)
forEach(callbackFn[, thisArg])
// Inline anonymous function:
forEach(function (element) { /* … */ })
forEach(function (element[, index]) { /* … */ })
forEach(function (element[, index[, array]]) { /* … */ })
forEach(function (element[, index[, array]]) { /* … */ }[, thisArg])
How the Callback Works
The forEach()
function iterates over each element in the array and calls the specified function. For every element, it passes the value, the index, and the original array as arguments to the callback. The callback is executed once for each element, and the number of executions matches the number of elements in the array.
Return value
The forEach()
function always returns undefined
. It does not create a new array.
const numbers = [1, 2, 3, 4, 5];
const result = numbers.forEach(function(number) {
return number * 2; // Even if a value is returned, forEach() still returns undefined
});
console.log(result); // Output: undefined
Examples of Using forEach()
The forEach()
function is ideal for performing operations on each element of an array. Since it doesn't return a value, it’s primarily used for executing actions or side effects rather than generating new arrays.
Here are some common use cases where forEach()
can be applied:
- Printing array elements
- Summing array values
- Finding elements that match a condition
- Transforming elements into strings
- Modifying object properties within the array
- Understanding when
forEach()
might not be the best choice
Printing array elements
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
}); // Output: 1 2 3 4 5
Summing array values
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach(function(number) {
sum += number;
});
console.log(sum); // Output: 15
Finding elements that match a condition
const numbers = [10, 25, 30, 45];
let foundNumber = null;
numbers.forEach(function(number) {
if (number > 30) {
foundNumber = number;
}
});
console.log(foundNumber); // Output: 45
Transforming elements into strings
const names = ['Alice', 'Bob', 'Charlie'];
const greetings = [];
names.forEach(function(name) {
greetings.push(`Hello, ${name}!`);
});
console.log(greetings); // Output: ['Hello, Alice!', 'Hello, Bob!', 'Hello, Charlie!']
Code Explanation
The push()
function adds one or more elements to the end of the array.
Modifying object properties within the array
const people = [
{name: 'Alice', age: 30},
{name: 'Bob', age: 25},
{name: 'Charlie', age: 35}
];
people.forEach(function(person) {
person.age += 5;
});
console.log(people);
/* Output:
[
{name: 'Alice', age: 35},
{name: 'Bob', age: 30},
{name: 'Charlie', age: 40}
]
*/
Understanding when forEach()
might not be the best choice
While forEach()
is useful for many tasks, there are situations where using a different approach is more appropriate.
When you need to break the loop early
const numbers = [1, 2, 3, 4];
let foundNumber = null;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 3) {
foundNumber = numbers[i];
break;
}
}
console.log(foundNumber); // Output: 4
Code Explanation
The for
loop allows for conditional interruption using break
.
Code Explanation
The break
statement exits the current loop immediately and passes control to the next statement.
When you need to return a new array
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Code Explanation
The map()
function creates a new array by applying a transformation function to each element of the original array.
Differences Between forEach()
and map()
The JavaScript forEach()
and map()
functions both iterate over array elements and process them using a callback function. However, the key difference is that forEach()
is used for simply performing operations on each element, while map()
transforms each element using the callback function and returns a new array.
Here’s a code example illustrating the difference between forEach()
and map()
:
// Original array
const numbers = [1, 2, 3, 4, 5];
// Using forEach()
const squaredNumbersForEach = [];
numbers.forEach(function(number) {
squaredNumbersForEach.push(number * number);
});
console.log("Using forEach():", squaredNumbersForEach);
// Output: "Using forEach():" [1, 4, 9, 16, 25]
// Using map()
const squaredNumbersMap = numbers.map(function(number) {
return number * number;
});
console.log("Using map():", squaredNumbersMap);
// Output: "Using map():" [1, 4, 9, 16, 25]
In the example above, the forEach()
function iterates over each element, calculates its square, and manually adds the result to squaredNumbersForEach
. It does not return a new array—side effects like pushing values to another array must be handled manually.
On the other hand, the map()
function automatically returns a new array, squaredNumbersMap
, where each element is the result of squaring the corresponding element in the original array.
Pros and Cons of forEach()
and map()
Both forEach()
and map()
have their strengths and weaknesses. Depending on your use case, one may be better suited than the other.
Advantages of forEach()
- Offers a more concise syntax than
map()
when return values are not needed. - Does not require handling a return value—ideal for performing actions like logging or updating external data.
- Allows direct modification of the original array, which can be useful in some scenarios.
Disadvantages of forEach()
- Cannot be used to create or return a new array.
- Not suitable for chaining or functional transformations.
Advantages of map()
- Returns a new array with transformed values.
- Produces an array of the same length as the original, with updated elements.
- Keeps the original array unmodified, supporting immutable coding practices.
Disadvantages of map()
- Creates a new array in memory, which may affect performance on large datasets.
- Can result in slightly longer or more complex code than
forEach()
.
In general, map()
is the better choice when you want to transform an array and return the result. However, forEach()
can be the more convenient option when you simply want to perform actions on elements without generating new data.
Overall, map()
is generally more useful for processing arrays when you need a new transformed array. However, forEach()
is simpler and may be more convenient for situations where you only need to perform actions on elements without producing new arrays.
Browser compatibility
method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
forEach()
|
1 | 12 | 1.5 | 3 |
Specifications
Specification | |
---|---|
forEach()
|
ECMAScript Language Specification #sec-array.prototype.foreach |