In the previous post we looked at the for...of
and for...in
loops in JavaScript. In this post we will look at the forEach
loop.
Structure
array.forEach(function() {
//...
});
The forEach
method is composed of a callback function with minimum of 1 argument and a maximum 3:
- element - The current element that the iterator is on.
- index (optional) - The index of the element that the iterator is on.
- array (optional) - The array that
forEach
is iterating over.
Let’s look at some examples:
const array = [1,3,5,7];
array.forEach(function(element) {
console.log(element); //1
//3
//5
//7
});
You can also use arrow functions for the example above:
array.forEach(element => console.log(element)); //1
//3
//5
//7
Using the Optional Parameters
Using index
array.forEach((element, index) => {
console.log(`Index: ${index} Value: ${element}`); //Index: 0 Value: 1
}); //Index: 1 Value: 3
//Index: 2 Value: 5
//Index: 3 Value: 7
Using array
array.forEach((element, index, array) => {
console.log (array); //[ 1, 3, 5, 7 ]
//[ 1, 3, 5, 7 ]
//[ 1, 3, 5, 7 ]
//[ 1, 3, 5, 7 ]
});