forEach() Array Method
The forEach()
array method is a built-in method in JavaScript that allows you to iterate over an array and apply a callback function to each element in the array. This method is typically used to perform some action on each element in an array without the need for a for loop or other iteration construct.
Here is a quick example:
var numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
We can use forEach()
to iterate over the numbers
array and instead of logging to console, we could theoretically do a calculation or perform another action on the items in the array.
Syntax and Parameters
array.forEach(function(element, index, array) {
// code to be executed for each element
}, this);
Parameter | Description | Optional/Required |
---|---|---|
function | The callback function to be applied to each element | Required |
element | The current element being processed | Required |
index | The index of the current element being processed | Optional |
array | The array that the forEach() method was called on | Optional |
this | Defaults to undefined. A value passed to the function as its this value. | Optional |
forEach()
method examples:
Add a class to each element in an array:
var elements = document.querySelectorAll('div');
elements.forEach(function(element) {
element.classList.add('highlight');
});
You may also want to check out:
map()
filter()
reduce()