Array.forEach()
The Array.forEach()
method in JavaScript is used to execute a provided callback function once for each array element. It is commonly used for performing side effects like logging or modifying external variables but does not return a new array or change the original array.
Syntax
forEach(callbackFn)
forEach(callbackFn, thisArg)
Parameters
Parameter | Description |
---|---|
callbackFn | A function to execute on each element of the array. It takes three arguments: |
| |
thisArg | Optional. A value to use as this when executing callbackFn . |
Return Value
The forEach()
method does not return a value. It always returns undefined
.
Examples
1. Iterating Over Array Elements
This example demonstrates how to iterate over array elements using the forEach()
method.
const numbers = [10, 20, 30];
numbers.forEach((num) => {
console.log(num);
});
Output
10
20
30
Here, the callbackFn
is executed for each element of the array, logging its value to the console.
2. Accessing Index and Array
The callback function can also access the index and the original array.
const fruits = ["apple", "banana", "cherry"];
fruits.forEach((fruit, index, array) => {
console.log(`Index: ${index}, Fruit: ${fruit}, Array: ${array}`);
});
Output
Index: 0, Fruit: apple, Array: apple,banana,cherry
Index: 1, Fruit: banana, Array: apple,banana,cherry
Index: 2, Fruit: cherry, Array: apple,banana,cherry
This demonstrates the use of all three arguments in the callback function: currentValue
, index
, and array
.
3. Using thisArg
The thisArg
parameter allows you to specify the value of this
inside the callback function.
const multiplier = {
factor: 2,
};
const numbers = [1, 2, 3];
numbers.forEach(function (num) {
console.log(num * this.factor);
}, multiplier);
Output
2
4
6
Here, the thisArg
is set to the multiplier
object, allowing the callback function to access this.factor
.
4. Modifying External Variables
The forEach()
method can be used to modify variables outside of its scope.
const numbers = [1, 2, 3];
let sum = 0;
numbers.forEach((num) => {
sum += num;
});
console.log(sum);
Output
6
In this example, the variable sum
is updated during each iteration of the forEach()
loop.