Table of Contents
The Short Answer
map() transforms: it returns a new array containing the result of each function call.
forEach() performs actions: it runs a function on each item and returns undefined.
let numbers = [1, 2, 3]; let doubled = numbers.map(n => n * 2); console.log(doubled); // [2, 4, 6] let result = numbers.forEach(n => n * 2); console.log(result); // undefined
What map() Does
Runs a function on every item: from the first to the last.
Returns a new array: it always has the same length as the original.
Uses the value your function returns: each returned value becomes an item in the new array.
Leaves the original array alone: nothing is changed.
let names = ["vi", "sam", "alex"]; let upper = names.map(name => name.toUpperCase()); console.log(upper); // ["VI", "SAM", "ALEX"] console.log(names); // ["vi", "sam", "alex"], unchanged
What forEach() Does
Runs a function on every item: from the first to the last.
Returns undefined: whatever your function returns is ignored.
Is meant for side effects: such as logging, updating a variable, or changing something on the page.
Leaves the original array alone: unless your function changes the items itself.
let names = ["vi", "sam", "alex"];
names.forEach(name => {
console.log(`Hello, ${name}`);
});
// Hello, vi
// Hello, sam
// Hello, alex
Comparing Them Side by Side
| Feature | map() | forEach() |
| Returns | A new array | undefined |
| Can be chained | Yes | No |
| Result length | Same as the original | Not applicable |
| Can stop early with break | No | No |
| Main purpose | Transforming data | Doing something with each item |
| Works well with await | No | No |
| Changes the original | No | No, unless you change the items yourself |
The Same Task, Both Ways
Building a list of prices with tax:
let prices = [100, 200, 300];
// With map(): clean and direct
let withTax = prices.map(price => price * 1.18);
console.log(withTax); // [118, 236, 354]
// With forEach(): needs an extra array and more code
let withTax2 = [];
prices.forEach(price => {
withTax2.push(price * 1.18);
});
console.log(withTax2); // [118, 236, 354]
Both give the same result: but map() is shorter and says exactly what it means.
Printing items to the console:
// With forEach(): the right choice, because nothing needs to be returned prices.forEach(price => console.log(price)); // With map(): works, but creates an unused array prices.map(price => console.log(price)); // returns [undefined, undefined, undefined]The second example is a misuse: map() builds an array that nobody uses.
Chaining
map() can be chained: because it returns an array.
let result = [1, 2, 3, 4, 5]
.map(n => n * 2)
.filter(n => n > 4)
.map(n => `Number: ${n}`);
console.log(result); // ["Number: 6", "Number: 8", "Number: 10"]
forEach() cannot be chained: it returns undefined, so there is nothing to continue with.
let broken = [1, 2, 3].forEach(n => n * 2).map(n => n); // TypeError
Real-World Examples
Use map() to reshape data:
let users = [
{ name: "Vi", age: 22 },
{ name: "Sam", age: 30 }
];
let names = users.map(user => user.name);
console.log(names); // ["Vi", "Sam"]
Use map() to build elements in React:
// const list = items.map(item => <li key={item.id}>{item.name}</li>);
Use forEach() to send something for each item:
users.forEach(user => {
console.log(`Sending email to ${user.name}`);
});
Use forEach() to add up a total:
let total = 0;
[10, 20, 30].forEach(n => {
total += n;
});
console.log(total); // 60
For totals, reduce() is usually cleaner:
console.log([10, 20, 30].reduce((sum, n) => sum + n, 0)); // 60
Things They Have in Common
Neither can be stopped with break: the loop always visits every item.
Both skip empty slots: in arrays with gaps.
Both receive the item, the index and the array: in that order.
["a", "b"].map((item, index, array) => `${index}: ${item}`);
// ["0: a", "1: b"]
Neither waits for await: an async function inside either method does not pause the loop.
For async work, use for...of:
async function run(items) {
for (let item of items) {
await doSomething(item);
}
}
When to Use Each One
Use map() when:- You need a new array built from the old one.
- You want to chain other methods, such as filter() or reduce().
- You are converting data from one shape to another.
- You are building a list of elements to display.
- You only want to do something with each item, such as logging.
- You do not need anything returned.
- You are updating something outside the array.
- You are triggering an action for each item.
- You need to stop early with break.
- You need to use await inside the loop.
Common Mistakes
Using forEach() and expecting a new array: it always returns undefined.
Using map() when you do not need the result: this creates an array that is thrown away.
Forgetting to return a value inside map(): with curly braces, you need an explicit return, or you get an array of undefined.
let broken = [1, 2, 3].map(n => { n * 2 });
console.log(broken); // [undefined, undefined, undefined]
let fixed = [1, 2, 3].map(n => { return n * 2; });
console.log(fixed); // [2, 4, 6]
Trying to break out of either one: it will not work, so use a regular loop instead.
Using await inside them: the loop will not wait, so things can run out of order.
Conclusion
The choice comes down to one question: do you need a new array back? If you do, use map(). If you only want to do something with each item, use forEach(). When you notice yourself pushing results into an empty array inside a forEach(), that is usually a sign that map() would be cleaner.Frequently Asked Questions (FAQs)
1.What is the main difference between map() and forEach()?2.Is map() faster than forEach()?map() returns a new array with the results, while forEach() returns undefined.
3.Can I use map() without using the result?The speed difference is usually too small to matter. Choose based on whether you need a new array.
You can, but it is considered poor practice, because it builds an array that is never used. Use forEach() for that purpose instead.
0 Comments