forEach Method
This is an array iteration method that is used as a replacement for the for
and for...of
loops when working with a data collection.
array.forEach(function callback(element, index, array) {
// Callback body
});
- Iterates over an array element by element.
- Calls a callback function for each element of the array.
- Returns nothing.
Callback arguments are the value of the current element
element, its index
index and the original array
. You can declare only those parameters that are required – most often this is an element – but never forget about their order.
const numbers = [5, 10, 15, 20, 25];
// Classic for
for (let i = 0; i < numbers.length; i += 1) {
console.log(`Index ${i}, value ${numbers[i]}`);
}
// Iterating forEach
numbers.forEach(function (number, index) {
console.log(`Index ${index}, value ${number}`);
});
The only case where you should use for
or for...of
loops to iterate over an array is a task with loop interruption. You cannot interrupt the execution of the forEach
method, as it always iterates over the array to the end.