map: Transforming Every Element
map calls your function on every element in an array and returns a new array with the transformed values. The original array is never changed.
map always returns an array with the same length. Use it for transformation. Use forEach for side effects. Wrap returned objects in parentheses with arrow functions.
EXERCISE
1map() Creates a New Array by Transforming Each Element
The map method calls your function once for every element in an array and creates a brand new array from the results. The original array is never changed.
map calls your function once for every element and collects the return values into a new array. The result always has the same length as the original, and the original is never modified.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [2, 4, 6, 8]
console.log(numbers); // [1, 2, 3, 4]
The second line matters as much as the first. map builds a new array, so anything else holding numbers still sees what it always saw. That is what makes it safe to use on data you did not create.
The callback receives three arguments, and the second is often useful:
const letters = ["a", "b", "c"];
const labelled = letters.map((value, index) => index + ": " + value);
console.log(labelled); // ["0: a", "1: b", "2: c"]
value, index, and the whole array as a third parameter. Take only the ones you need.
That signature causes a well-known trap when you pass a named function directly:
console.log(["1", "2", "3"].map(Number)); // [1, 2, 3]
console.log(["1", "2", "3"].map(parseInt)); // [1, NaN, NaN]
Number takes one argument and ignores the rest. parseInt takes two: the string and a radix. map supplies the index as that second argument, so the calls become parseInt("2", 1) and parseInt("3", 2), neither of which is valid. Writing (s) => parseInt(s, 10) passes only what you meant.
Every returned value is kept, including the ones you did not mean to return:
const prices = [10, 20, 30];
const wrong = prices.map((p) => {
p * 1.2;
});
console.log(wrong); // [undefined, undefined, undefined]
The braces made the body a block with no return, so every call produced undefined and map faithfully collected three of them. Either remove the braces or add return.
Pro Tip: If the result of
mapis an array ofundefined, the callback is not returning. If you did not want the result at all,forEachis the honest choice, because it says so.
map skips holes in a sparse array but keeps them in the result, which is worth knowing before you meet it:
const sparse = [1, , 3];
console.log(sparse.map((n) => n * 2)); // [2, empty, 6]
The callback never ran for the missing index, so no value was produced for it. Sparse arrays are rare in code people write deliberately and common in code that assigns past the end of an array.
EXERCISE
2map() with Objects
map() shines when working with arrays of objects. You can extract specific fields, reshape data, or compute new values from each object.
Most real arrays hold objects rather than numbers, and map is how you reshape them.
const users = [
{ id: 1, first: "Ada", last: "Lovelace" },
{ id: 2, first: "Alan", last: "Turing" },
];
const names = users.map((u) => u.first + " " + u.last);
console.log(names); // ["Ada Lovelace", "Alan Turing"]
Extracting one field is the most common use of all, and it is worth knowing the arrow-with-object trap here, because the fix looks like noise:
const shaped = users.map((u) => ({ id: u.id, name: u.first }));
console.log(shaped); // [{ id: 1, name: "Ada" }, { id: 2, name: "Alan" }]
The parentheses around the object are required. Without them the braces are read as a function body and the function returns nothing.
Copying an object rather than mutating it:
const products = [
{ name: "book", price: 20 },
{ name: "pen", price: 5 },
];
const discounted = products.map((p) => ({ ...p, price: p.price * 0.9 }));
console.log(discounted[0].price); // 18
console.log(products[0].price); // 20
{ ...p, price: ... } builds a new object with all of p's properties and then overrides one. The original is untouched, which is the behaviour map promises for the array and does not automatically give you for the objects inside it.
That distinction catches people, so it is worth seeing the version that breaks it:
const wrong = products.map((p) => {
p.price = p.price * 0.9;
return p;
});
console.log(products[0].price); // 18, the original changed
map did create a new array, but every element in it is the same object that was in the old one. Modifying p modified the original, and now both arrays show the discount. The array was copied; the objects were not.
This is the reference behaviour from the objects lesson applied to a whole collection, and it is the single most common way an operation that looks purely functional turns out to mutate shared state.
When the shape change is larger, a named function keeps the chain readable:
function toRow(user) {
return {
id: user.id,
label: user.first + " " + user.last,
initial: user.first[0],
};
}
const rows = users.map(toRow);
console.log(rows[0].initial); // "A"
toRow can be tested on a single object without involving an array at all, and the map line now states what it does rather than how.
EXERCISE
3When NOT to Use map()
map() is for transformation. If you are not building a new array from the results, you should use forEach() or a for loop instead.
map means "transform every element into a new one". When that is not what you are doing, a different method says so more clearly and often does less work.
If you are not using the result, use forEach:
const names = ["Ada", "Alan"];
names.forEach((n) => console.log(n));
Written with map, this would build an array of undefined and throw it away. Nothing breaks, but the code claims to produce a value and does not, which is a small lie the next reader has to check.
If you are removing elements, use filter:
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter((n) => n % 2 === 0);
console.log(evens); // [2, 4, 6]
map cannot shorten an array. Its result is always the same length, so selecting a subset is not something it can express.
If you are combining everything into one value, use reduce:
const prices = [10, 20, 30];
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total); // 60
If you are looking for one element, use find:
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Alan" },
];
const user = users.find((u) => u.id === 2);
console.log(user.name); // "Alan"
find returns the element itself rather than an array, and stops at the first match instead of walking the whole collection. filter(...)[0] gives the same answer after doing more work and returns undefined in a less obvious way when nothing matches.
| You want | Use |
|---|---|
| a new value for every element | map |
| a subset of the elements | filter |
| one value from all of them | reduce |
| the first matching element | find |
| whether any match | some |
| whether all match | every |
| a side effect, no result | forEach |
Choosing correctly is not about performance. It is that the method name tells the next reader what the block does before they read it, and map used for everything tells them nothing.
Pro Tip: A
mapwhose callback contains anifwith noelseis usually afilter, afind, or both. The missing branch has to return something, and that something is normallyundefinedsitting in your result.
