forEach()
The forEach()
array method in JavaScript executes a provided function once for each element in an array, in ascending index order.
Syntax
array.forEach(function(currentValue, index, array) {
// your code here
});
Parameters:
- function: Callback function to execute for each element, taking three possible arguments:
- currentValue: The current element being processed.
- index (optional): The index of the current element.
- array (optional): The original array
forEach()
was called upon.
Basic usage
Let's look at the simplest example using a pizza toppings array:
const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
pizzaToppings.forEach(function(topping) {
console.log(`I like ${topping} on my pizza`);
});
// Output:
// I like Cheese on my pizza
// I like Pepperoni on my pizza
// I like Mushrooms on my pizza
// I like Olives on my pizza
Using the index parameter
The second parameter gives you access to the current index position, beginning at zero:
const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
pizzaToppings.forEach(function(topping, index) {
console.log(`Topping #${index + 1}: ${topping}`);
});
// Output:
// Topping #1: Cheese
// Topping #2: Pepperoni
// Topping #3: Mushrooms
// Topping #4: Olives
The function can also be extracted from the forEach
method, making it more readable and re-usable:
const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
pizzaToppings.forEach(listToppings);
function listToppings(topping, index) {
console.log(`Topping #${index + 1}: ${topping}`);
}
// Output:
// Topping #1: Cheese
// Topping #2: Pepperoni
// Topping #3: Mushrooms
// Topping #4: Olives
Using the array parameter
The third parameter provides reference to the original array:
const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives'];
pizzaToppings.forEach(function(topping, index, array) {
const newName = "Double " + topping
console.log("new name: " + newName + " | old name: " + array[index])
});
// Output:
// "new name: Double Cheese | old name: Cheese"
// "new name: Double Pepperoni | old name: Pepperoni"
// "new name: Double Mushrooms | old name: Mushrooms"
// "new name: Double Olives | old name: Olives"
Working with arrays of objects
The forEach()
method is useful when working with arrays of objects:
const pizzaMenu = [
{ name: 'Margherita', price: 10, toppings: ['Sauce', 'Mozzarella', 'Basil'] },
{ name: 'Pepperoni', price: 12, toppings: ['Sauce', 'Mozzarella', 'Pepperoni'] },
{ name: 'Vegetarian', price: 13, toppings: ['Sauce', 'Mozzarella', 'Mushrooms', 'Peppers', 'Olives'] }
];
// Print each pizza with its toppings
pizzaMenu.forEach(function(pizza) {
console.log(`${pizza.name} - $${pizza.price}`);
pizza.toppings.forEach(function(topping, index) {
console.log(` ${index + 1}. ${topping}`);
});
console.log('~ ~ ~');
});
// Output:
// "Margherita - $10"
// " 1. Sauce"
// " 2. Mozzarella"
// " 3. Basil"
// "~ ~ ~"
// "Pepperoni - $12"
// " 1. Sauce"
// " 2. Mozzarella"
// " 3. Pepperoni"
// "~ ~ ~"
// "Vegetarian - $13"
// " 1. Sauce"
// " 2. Mozzarella"
// " 3. Mushrooms"
// " 4. Peppers"
// " 5. Olives"
// "~ ~ ~"
Modifying the original array
Unlike map
, forEach()
can be used to modify the original array. Here is an example using the arrow function syntax:
const pizzaPrices = [10, 12, 13, 15];
// Apply 10% discount to all prices
pizzaPrices.forEach((price, index, array) => {
array[index] = Math.round(price * 0.9);
});
console.log(pizzaPrices); // [9, 11, 12, 14]
Error handling in forEach
You can use try-catch inside the callback function:
const specialPizzas = ['Hawaiian', 'Extra Hot Pepperoni', 'BBQ Chicken'];
specialPizzas.forEach(pizza => {
try {
if (pizza === 'Extra Hot Pepperoni') {
throw new Error('Pizza sold out');
}
console.log(`${pizza} pizza is available.`);
} catch (error) {
console.error(`Error with ${pizza}: ${error.message}`);
}
});
Practical example: calculating total price
const pizzaOrder = [
{ name: 'Margherita', price: 10, quantity: 2 },
{ name: 'Pepperoni', price: 12, quantity: 1 },
{ name: 'Supreme', price: 15, quantity: 1 }
];
let totalPrice = 0;
let totalItems = 0;
pizzaOrder.forEach(pizza => {
const itemTotal = pizza.price * pizza.quantity;
totalPrice += itemTotal;
totalItems += pizza.quantity;
console.log(`${pizza.quantity}x ${pizza.name}: $${itemTotal}`);
});
console.log(`----------`);
console.log(`Total items: ${totalItems}`);
console.log(`Total price: $${totalPrice}`);
When to use forEach vs. other methods
Use forEach()
when:
- You want to modify/update the original array.
- You're performing side effects like DOM manipulation.
- You need to run code for each element but don't need to create a new array in the process.
Consider using other methods when:
- You need to create a new array based on the original (use
map()
) - You need to filter elements (use
filter()
) - You need to find a specific element (use
find()
orfindIndex()
) - You need to check if elements meet a condition (use
some()
orevery()
) - You need to accumulate a value (use
reduce()
)
Conclusion
The forEach()
method provides a clean and readable way to execute code for each element in an array. While it doesn't return a new array like map()
and can't be chained with other array methods, it's useful for when you need to perform operations on each element without creating a new array.