- Purpose: The forEach loops iterates over each item in an array, executing a callback function for each element.
- Syntax:
array.forEach(function(currentValue, index, arr), thisValue)
- Parameters:
-
currentValue: The current element being processed in the array. -
index(Optional): The index of the current element being processed. -
arr(Optional): The array theforEachloop is being applied to. -
thisValue(Optional): A value to use asthiswhen executing the callback.
-
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(function(item) {
console.log(item);
});const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(function(item, index) {
console.log(index, item);
});Before:
const images = document.querySelectorAll('img');
images[0].src = 'image1.jpg';
images[1].src = 'image2.jpg';
images[2].src = 'image3.jpg';After:
const imageSources = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
document.querySelectorAll('img').forEach((img, index) => {
img.src = imageSources[index];
});- Use
forEachfor side effects within a function. - Remember that
forEachdoesn't stop or break - it loops through the entire selected array.
Happy coding! 😊