, , , ,

Understanding forEach vs map in JavaScript: When to Use Each


JavaScript offers several ways to loop through arrays, but two of the most commonly confused methods are forEach and map. At first glance, they look similar—both iterate over arrays and execute a function for each element. However, their purposes are quite different.


The Core Difference

  • forEach → Executes a function for each element, primarily for side effects. It does not return a new array.
  • map → Transforms each element and returns a new array containing the results.

Think of forEach as a worker who performs tasks without producing a new product, while map is a worker who transforms raw materials into a new finished product.


🛠 When to Use forEach

Use forEach when you want to do something with each item but don’t need a new array. Typical use cases:

  • Logging values
  • Updating the DOM
  • Mutating external variables or states
const numbers = [1, 2, 3];
numbers.forEach(num => {
  console.log(num * 2); // Prints 2, 4, 6
});
// No new array is returned

🛠 When to Use map

Use map when you want to transform data and create a new array. Typical use cases:

  • Converting strings to uppercase
  • Extracting specific properties from objects
  • Performing calculations
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6]

Quick Comparison

FeatureforEachmap
Return valueundefinedNew transformed array
Use caseSide effects (logging, DOM, etc.)Data transformation
Chainable❌ No✅ Yes (can chain with filter, etc.)
Mutates array?❌ No (but can mutate external vars)❌ No (returns new array)

Rule of Thumb

  • Use forEach when you only need to do something with each item.
  • Use map when you need to create a new array of transformed items.

Common Mistakes to Avoid

  1. Using map for side effectsnumbers.map(num => console.log(num)); // Returns [undefined, undefined, undefined]👉 Wrong tool. Use forEach instead.
  2. Expecting forEach to return a new arrayconst doubled = numbers.forEach(num => num * 2); console.log(doubled); // undefined👉 Wrong expectation. Use map for transformations.

🌍 Real-World Examples

1. Transforming API Responses (Use map)

Imagine you fetch a list of users from an API and want only their names:

const users = [
  { id: 1, name: "Alice", age: 25 },
  { id: 2, name: "Bob", age: 30 },
  { id: 3, name: "Charlie", age: 35 }
];

const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob", "Charlie"]

👉 Perfect use of map because you’re transforming data into a new array.


2. Updating the UI (Use forEach)

Suppose you want to render each user’s name into the DOM:

users.forEach(user => {
  const li = document.createElement("li");
  li.textContent = user.name;
  document.querySelector("#userList").appendChild(li);
});

👉 Perfect use of forEach because you’re performing side effects (DOM updates), not creating a new array.


3. Calculating Discounts (Use map)

You have product prices and want to apply a 10% discount:

const prices = [100, 200, 300];
const discounted = prices.map(price => price * 0.9);

console.log(discounted); // [90, 180, 270]

👉 map is ideal because you’re transforming values into a new array.


4. Logging Analytics (Use forEach)

You want to log each product purchase for analytics:

const purchases = ["Laptop", "Phone", "Tablet"];
purchases.forEach(item => {
  console.log(`User bought: ${item}`);
});

👉 forEach is ideal because you’re triggering side effects (logging).


Conclusion

Both forEach and map are powerful, but they serve different purposes. If you’re transforming data, reach for map. If you’re performing side effects, stick with forEach. Knowing when to use each will make your code cleaner, more efficient, and easier to understand.


Leave a Reply

Your email address will not be published. Required fields are marked *