JavaScript map() vs forEach(): What’s the Difference?
When working with arrays in JavaScript, two of the most commonly used methods are map()
and forEach()
. While they may look similar at first glance—both iterate over an array—there are key differences in how they work and when to use each.
Let’s dive into the comparison between map()
and forEach()
.
🔍 1. What is forEach()
?
The forEach()
method executes a provided function once for each array element. It’s typically used when you want to perform side effects (e.g., logging, modifying external variables), but you don’t need a returned array.
📦 Example:
const numbers = [1, 2, 3];
numbers.forEach(num => {
console.log(num * 2); // Output: 2, 4, 6
});
- 🔁 Iterates over each item
- ❌ Does not return a new array
- ⚠️ Can’t be chained
🔁 2. What is map()
?
The map()
method creates a new array populated with the results of calling a function on every element.
📦 Example:
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
- ✅ Returns a new array
- ✅ Pure function – does not modify original array
- ✅ Can be chained (e.g.,
.map().filter()
)
⚖️ 3. Key Differences Between map()
and forEach()
Feature | map() | forEach() |
---|---|---|
Return value | ✅ Returns a new array | ❌ Returns undefined |
Use case | Transform data (pure function) | Side effects (e.g., logging) |
Mutability | Does not change original array | Does not change original array |
Chainable | ✅ Yes | ❌ No |
Performance | Similar, but use-case dependent | Similar |
🧠 When to Use Each?
- ✅ Use
map()
when:- You want to transform data into a new array
- You’re applying a function that returns a value
- You need to chain with
.filter()
or.reduce()
- ✅ Use
forEach()
when:- You’re doing side effects like logging, DOM manipulation, or saving data
- You don’t need to create a new array
❌ Common Mistake
const result = numbers.forEach(num => num * 2);
console.log(result); // ❌ undefined
People often mistakenly use forEach()
expecting it to return a new array. Only map()
is designed for that.
🧪 Bonus: Can map()
replace forEach()
?
Technically yes—but it’s not recommended when your intention is side effects only. Using map()
just to loop through and do something like console.log()
is a misuse of its purpose.
// ⚠️ Anti-pattern: using map for side effects only
numbers.map(num => console.log(num)); // Use forEach instead
📝 Summary
Method | Purpose | Returns | Side Effects | Chainable |
---|---|---|---|---|
map() | Transform data | New array | ❌ Avoided | ✅ Yes |
forEach() | Perform action | undefined | ✅ Common | ❌ No |
💬 Final Tip (Interview Style)
Use
map()
when you need a new array from your data.
UseforEach()
when you’re just iterating and doing things like logging or updating UI.
Comments are closed.