58. Array Iteration: The .forEach() Method
.forEach() is a high-order array method. It executes a provided function once for each array element.
Syntax
javascript array.forEach(function(currentValue, index, array) { // do something with currentValue });
Example: Logging Users
javascript const users = ['Anya', 'Ben', 'Chloe'];
users.forEach(function(name, index) {
// The function passed to forEach is called a 'callback function'
console.log(${index + 1}. ${name});
});
// We will use modern arrow function syntax (covered later) for brevity: users.forEach(user => console.log(user.toUpperCase()));
Key Limitation of .forEach()
- No Return Value:
forEach()always returnsundefined. It is only used for side effects (like logging to the console, or updating the DOM). - Cannot
break: You cannot usebreakorcontinueinside aforEachloop; you must complete all iterations.