forEach method
The forEach
method allows you
to sequentially iterate through all
the elements of an array. The method
in the parameter receives a function
that will be executed for each element
of the array.
Three parameters can be passed to this function. If these parameters are present (they are not required), then the first one will automatically get the array element, the second one will get its number in the array (index), and the third one will get the array itself.
Syntax
array.forEach(function(element, index, array) {
a code to be executed for all elements
});
Example
Let's output the elements of an array to the console:
let arr = [1, 2, 3, 4, 5];
arr.forEach(function(elem) {
console.log(elem);
});
Example
Let's output elements and their indices to the console:
let arr = ['a', 'b', 'c', 'd', 'e'];
arr.forEach(function(elem, ind) {
console.log(elem, ind);
});
Example
Let's find the sum of the array elements:
let arr = [1, 2, 3, 4, 5];
let sum = 0;
arr.forEach(function(elem) {
sum += elem;
});
console.log(sum);
The code execution result:
15