Arrays
array.map()
Builds a new array by turning every item of the original into something else.
Why it exists
Data almost never arrives in the shape you need to show it: the server sends product objects, but the screen needs cards; you have prices in dollars but need euros; you have users but need a list of names. map describes the rule for turning one item and applies it to all of them. In React, that's how every list on a page is rendered: items.map((item) => <Card … />).
Where it's used
- Rendering lists in React:
products.map((p) => <ProductCard product={p} />). - Pulling out one field:
users.map((u) => u.email). - Recalculating values: discounted prices, currency conversion, rounding.
- Reshaping server data before showing it.
Syntax
const result = array.map((item) => newValue);Examples
const products = [
{ title: "Tea", price: 3 },
{ title: "Coffee", price: 5 },
];
const titles = products.map((p) => p.title);
titles; // → ["Tea", "Coffee"]const prices = [100, 250];
prices.map((p) => p * 0.9); // → [90, 225]const users = [{ name: "Ann" }, { name: "Bob" }];
users.map((u, i) => i + 1 + ". " + u.name); // → ["1. Ann", "2. Bob"]const items = [{ title: "Tea", price: 3 }];
const sale = items.map((item) => ({ ...item, price: item.price - 1 }));
sale; // → [{ title: "Tea", price: 2 }]
items[0].price; // → 3 — the original objects are intactResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
map walks the array, calls the callback for each item and puts the callback's results into a new array — at the same positions. That's why the result always has the same length as the original.
The callback receives the item, its index and the whole array, and returns the new value. Whatever it returns ends up in the result, even undefined.
The original array isn't changed. But if the callback modifies object properties (p.price = …), the original objects change too — it's better to return new ones: ({ ...p, price: … }).
In essence, map is a loop that pushes each result, tucked inside a method.
Traps
How it differs from…
array.filter()filter decides whether to keep an item;
mapdecides what to turn each one into. Together:filter(…).map(…).for...ofloopA loop fits when you need to do something with each item rather than get a new array.
When to pick something else
Practice
Lessons where this appears
- The conveyor at the fish factoryTale · Chapter 10 · map, filter, reduce
- Why map and not a loop?Why? · Chapter 10 · map, filter, reduce
- A shift on the conveyorWorkshop · Chapter 10 · map, filter, reduce
- The case of the blank price tagsInvestigation · Chapter 10 · map, filter, reduce
- Names of adultsLab · Chapter 10 · map, filter, reduce
- The jammed conveyorBoss · Chapter 10 · map, filter, reduce