forEach()
ES5+Executes a provided function once for each array element.
Syntax
array.forEach(callback(element, index, array), thisArg)Parameters
callback Function Function to execute on each element
Return Value
undefined - forEach does not return a value
Examples
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(index + ': ' + fruit);
}); 📌 When to Use
Use forEach() when you need to execute side effects for each element, such as logging, updating external variables, or manipulating the DOM. Choose forEach() when you don't need to return a transformed array.
⚠️ Common Mistakes
Trying to break out of forEach() early - use for...of or some() instead
Using forEach() when you need the transformed result - use map() instead
Expecting forEach() to wait for async callbacks - it doesn't await promises
✅ Best Practices
Use for...of with await for async operations instead of forEach()
Prefer map(), filter(), or reduce() when building new data structures
Keep forEach() callbacks simple and focused on a single side effect
⚡ Performance Notes
forEach() has slightly more overhead than a traditional for loop due to function call overhead for each iteration. For performance-critical code with millions of iterations, consider a for loop. However, forEach() is typically fast enough for most use cases.
🌍 Real World Example
Updating DOM Elements
Apply styling or event listeners to a list of DOM elements
const buttons = document.querySelectorAll('.action-btn');
buttons.forEach((button, index) => {
button.addEventListener('click', handleClick);
button.dataset.index = index;
button.classList.add('initialized');
});
// Each button now has a click handler and index data