Mastering the forEach() Method in JavaScript
Introduction
The forEach() method in JavaScript is used to execute a provided function once for **each** array element. It's a cleaner and more readable alternative to using traditional for loops when you want to iterate over an array. 🔄
📌 What is forEach()?
forEach() is an **array iteration method** that applies a function to every item in the array. It does not return a new array — its main purpose is to perform side effects, like logging values or updating variables.
- ✔️ Executes a callback for every element
- 🚀 Automatically handles the iteration logic
- 🛑 Cannot be stopped early (unlike a for loop)
💡 Syntax
Basic Syntax
array.forEach(function(element, index, array) {
// Do something with element
}, thisArg)Parameters:
- element — Current item in the array
- index — (Optional) Index of the current item
- array — (Optional) The array itself
- thisArg — (Optional) Value to use as this when executing the callback
🧵 Example: Logging Array Elements
Log all elements with their indexes
const fruits = ["apple", "banana", "cherry"];
fruits.forEach((fruit, index) => {
console.log(index, fruit);
});
// Output:
// 0 'apple'
// 1 'banana'
// 2 'cherry'🍏 Example: Calculating Total
Sum array values
const prices = [10, 20, 30];
let total = 0;
prices.forEach(price => {
total += price;
});
console.log(total); // 60⚠️ Important Notes
Note
- forEach() always returns undefined — it’s for performing actions, not producing values.
- You cannot use break or return to stop it early.
- For creating a transformed array, use map() instead.
📊 Quick Reference Table
| Example | Output |
|---|---|
| [1, 2, 3].forEach(n => console.log(n)) | Logs 1, 2, 3 |
| ["a","b"].forEach(l => console.log(l.toUpperCase())) | Logs "A", "B" |
>>"forEach() is perfect when you want to do something with every item — no more, no less."
🔥 Summary
The forEach() method is ideal for performing actions on each element of an array without creating a new one. Use it for logging, calculations, or applying side effects in a clean and readable way.