JavaScript Roadmap — Day 34: Array Iteration — forEach() Method

 

 

Day 34 of 180 šŸ• 13 min read · ⚡ Intermediate Phase

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.

Traditional for loop vs forEach()
// Traditional for loop — verbose
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// forEach() — clean and declarative
fruits.forEach(function(fruit) {
  console.log(fruit);
});

// Even cleaner with arrow function
fruits.forEach(fruit => console.log(fruit));

šŸ’” 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.

forEach() Parameters
let fruits = ["apple", "banana", "cherry"];

// Only the element (most common)
fruits.forEach(fruit => {
  console.log(fruit);
});

// Element + Index
fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});

// Element + Index + Array
fruits.forEach((fruit, index, array) => {
  console.log(`${fruit} is at index ${index} of [${array}]`);
});
šŸ“ QUIZ Test Your Understanding

Question 1: What does forEach() return?

3. forEach() — Practical Examples

Here are common real-world use cases for forEach():

Real-World Examples
// Example 1: Sum all numbers in an array
let numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach(num => sum += num);
console.log(sum);  // 15

// Example 2: Log each item with its index
let colors = ["red", "green", "blue"];
colors.forEach((color, index) => {
  console.log(`${index}: ${color}`);
});

// Example 3: Modify external array (create new array)
let prices = [10, 20, 30];
let withTax = [];
prices.forEach(price => {
  withTax.push(price * 1.1);
});
console.log(withTax);  // [11, 22, 33]

// Example 4: Update DOM elements
let items = ["Apple", "Banana", "Cherry"];
let list = document.querySelector("#myList");
items.forEach(item => {
  let li = document.createElement("li");
  li.textContent = item;
  list.appendChild(li);
});
šŸ“ QUIZ Test Your Understanding

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:

Feature for loop forEach()
ReadabilityMore verboseCleaner, declarative
Can use break/continue✅ Yes❌ No
Access to indexManual (i variable)Automatic (2nd parameter)
Return valueAny value you returnAlways undefined
Best forComplex logic, early exitSimple iteration, side effects
When to Use Each
// Use for loop when you need to break early
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === target) {
    console.log("Found!");
    break;  // ✅ forEach() cannot do this
  }
}

// Use forEach() for simple iteration without early exit
arr.forEach(item => {
  console.log(item);  // ✅ Clean and simple
});

5. Common Mistakes to Avoid

Mistakes & Fixes
// ❌ MISTAKE 1: Trying to use break or continue
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
  if (num === 3) {
    break;  // ❌ SyntaxError: Illegal break statement
  }
  console.log(num);
});

// ✅ FIX: Use a traditional for loop or return (continue doesn't work either)
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === 3) break;
  console.log(numbers[i]);
}

// ❌ MISTAKE 2: Expecting forEach() to return a value
let doubled = numbers.forEach(n => n * 2);
console.log(doubled);  // undefined (not [2,4,6,8,10])

// ✅ FIX: Use map() for transformations
let doubled = numbers.map(n => n * 2);

6. Best Practices — Professional Advice

šŸŽÆ Use forEach() for Side Effects
forEach() is perfect for logging, updating the DOM, or modifying external variables. Use map() or filter() when you need a new array.
šŸ“¦ Use Arrow Functions for Cleaner Code
arr.forEach(item => console.log(item)) is much cleaner than the traditional function syntax.
šŸ”„ Don't Use forEach() for Async Operations
forEach() doesn't wait for promises. Use for...of loop with async/await for asynchronous operations.
šŸ“ Use the Index Parameter When Needed
The second parameter gives you the index. Use it instead of tracking a separate counter variable.

7. Try It Yourself — forEach() Playground

Experiment with forEach() below. See how it iterates through array elements.

✏️ forEach() Playground
HTML
JAVASCRIPT
LIVE PREVIEW
šŸ’” Try each button to see forEach() in action!

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!)

šŸ”„ Challenge of the Day

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);
šŸŽÆ Key Takeaways Remember These
  • 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
šŸ’¼ Common Interview Questions Must Know

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.

šŸ“– Download forEach() Cheat Sheet
Quick reference for array iteration with forEach()
Next Lesson
Day 35 — Array Method — map()
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts