The forEach Method
You'll learn how to use forEach to execute a function for each element in an array without creating a new array.
What is forEach?
The forEach method is an array iteration tool that lets you run a function on every element in an array. Unlike methods that return new arrays, forEach is used for side effects — actions like logging to the console, updating external variables, or modifying objects.
Think of forEach like a tour guide walking you through a museum. The guide (your callback function) stops at each exhibit (array element) and does something — explains it, takes a photo, writes notes — but the museum itself doesn't change, and you don't build a new museum.
Basic Syntax
const numbers = [1, 2, 3, 4];
numbers.forEach(function(num) {
console.log(num * 2);
});
// Logs: 2, 4, 6, 8
The callback function receives three arguments (though you typically use just the first):
- The current element
- The current index
- The array itself
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(function(fruit, index) {
console.log(index + ': ' + fruit);
});
// Logs:
// 0: apple
// 1: banana
// 2: cherry
Key Characteristic
forEach always returns undefined. It doesn't build or return a new array — it just performs actions.
const result = [1, 2, 3].forEach(function(num) {
return num * 2; // This return value is ignored!
});
console.log(result); // undefined
Key Takeaway: Use forEach when you need to perform side effects (like logging or DOM updates) for each array element, not when you need to transform data into a new array.