The forEach()
method in Javascript is used to execute the provided function once for every element of the array. What this means is the forEach()
loops through an array and runs a function on every element of the array.
For example, let us declare an array numbers
consisting of integers from 1 to 6. To loop through numbers
we will use the forEach()
method. We need to pass a function to the forEach()
method. The first parameter of this function holds the current element of the array.
let numbers = [1, 2, 3, 4, 5 , 6];
numbers.forEach(function(element) {
console.log(element);
});
Output:
1
2
3
4
5
6
The forEach()
method in this example loops through each element and logs every element.
forEach() index
We can pass an optional second parameter to the callback function of the forEach()
method. This contains the array index of the current element.
let numbers = [1, 2, 3, 4, 5 , 6];
numbers.forEach(function(element, index) {
console.log(index);
});
Output:
0
1
2
3
4
5
forEach() third parameter
We can pass an optional third parameter to the callback function of the forEach()
method. This contains the original array if we need to modify the original array.
For example, if we need to modify the array numbers
such that each element in the array should be added by 2. We can make use of the third parameter.
let numbers = [1, 2, 3, 4, 5 , 6];
numbers.forEach(function(element, index, arr) {
arr[index] = element + 2;
});
console.log(numbers); // [3, 4, 5, 6, 7, 8]