JavaScript Roadmap — Day 34: Array Iteration — forEach() Method
Array Iteration — forEach() Method
The forEach() method executes a function once for each array element. It's a cleaner, more functional way to loop through arrays compared to traditional for loops.
1. The Problem — Looping Through Arrays Efficiently
You already know how to loop through arrays using for loops. But writing for (let i = 0; i < arr.length; i++) every time becomes repetitive. Wouldn't it be nicer to just say "for each element, do this"?
That's exactly what the forEach() method does. It's a higher-order function that takes a callback function and executes it for every element in the array. No need to manage index variables or loop conditions.
š” The insight: forEach() makes your code more readable and declarative. You focus on WHAT you want to do with each element, not HOW to loop through them.
2. forEach() Syntax — Understanding the Callback
The forEach() method takes a callback function that can accept up to three parameters:
- currentValue — The current element being processed (required)
- index — The index of the current element (optional)
- array — The array being traversed (optional)
The callback is executed for each element in the array. forEach() always returns undefined, so it's used for side effects (like logging, modifying external variables, or updating the DOM), not for creating new arrays.
Question 1: What does forEach() return?
3. forEach() — Practical Examples
Here are common real-world use cases for forEach():
Question 2: Which of the following is TRUE about forEach()?
4. forEach() vs Traditional for Loop — When to Use Which
Both methods loop through arrays, but they have different strengths:
5. Common Mistakes to Avoid
6. Best Practices — Professional Advice
arr.forEach(item => console.log(item)) is much cleaner than the traditional function syntax.7. Try It Yourself — forEach() Playground
Experiment with forEach() below. See how it iterates through array elements.
8. Practice Tasks
Task 1 — Easy: Log Each Fruit
Create an array of 5 fruits. Use forEach() to log each fruit to the console.
Task 2 — Medium: Calculate Total Price
Given let prices = [10, 20, 30, 40, 50], use forEach() to calculate the total price and log it.
Task 3 — Hard: Filter with forEach()
Use forEach() to create a new array containing only numbers greater than 10 from [5, 12, 8, 15, 3, 20]. (Even though filter() is better, practice with forEach!)
Given an array of words ["hello", "world", "javascript", "is", "awesome"], use forEach() to create a new array with the uppercase version of each word. Log both arrays.
š View Solution
let words = ["hello", "world", "javascript", "is", "awesome"];
let upperWords = [];
words.forEach(word => upperWords.push(word.toUpperCase()));
console.log("Original:", words);
console.log("Uppercase:", upperWords);
- forEach() executes a function once for each array element — perfect for side effects
- Returns undefined — use map() if you need a new array
- Cannot use break or continue — use a traditional for loop if you need early exit
- Callback receives currentValue, index, array — index is optional but useful
- Arrow functions make forEach() cleaner:
arr.forEach(x => console.log(x)) - Don't use forEach() with async operations — it won't wait for promises to resolve
❓ Q: What is the difference between forEach() and map()?
š” A: forEach() executes a function for each element and returns undefined. map() creates a new array with the results of calling a function on every element.
❓ Q: Can you use break or continue inside forEach()?
š” A: No, break and continue will cause syntax errors. Use a traditional for loop if you need early termination.
❓ Q: What does forEach() return?
š” A: forEach() always returns undefined. It's designed for side effects, not for producing values.