map
Transform every item.
You have a list of prices, and you need the prices with tax added. Or a list of names, and you need them in capitals. Map transforms every item, and gives you a brand new array.

- Prices with tax
- Names in capitals
- map transforms each one
One callback, every item
Map calls your callback for every item, and collects the return values into a new array. The new array always has the same length as the original. And the original isn't changed. Run it.
const prices = [10, 20, 30];
const withTax = prices.map(p => p * 1.2);
console.log(withTax);
const names = ["ana", "ben"];
console.log(names.map(n => n.toUpperCase()));
console.log(names.map((n, i) => `${i + 1}. ${n}`));
console.log("original:", prices);[ 12, 24, 36 ] [ 'ANA', 'BEN' ] [ '1. ana', '2. ben' ] original: [ 10, 20, 30 ]
Map instead of loops
Before map, you'd create an empty array, loop, and push each result. Map does all of that in one clear line, and it says exactly what you mean. Transform each item. The callback also receives the index, as a second argument, if you need it.
| key | value |
|---|---|
| map(fn) | new array, same length |
| fn(item, index) | called for each |
| Original | unchanged |
| Replaces | loop + push |
Mapping objects
Map is often used to turn one kind of object into another. Here we turn a list of products into lines of text for a receipt. And we can map to new objects too, adding a price with tax. The original array is never changed. Run it.
const products = [
{ name: "Tea", price: 3 },
{ name: "Cake", price: 4.5 },
];
const lines = products.map(p => `${p.name}: $${p.price.toFixed(2)}`);
console.log(lines);
const withTax = products.map(p =>
({ ...p, price: +(p.price * 1.2).toFixed(2) }));
console.log(withTax[1], products[1].price);[ 'Tea: $3.00', 'Cake: $4.50' ]
{ name: 'Cake', price: 5.4 } 4.5Summary
Map transforms every item into a new array of the same length. Next, filter, which keeps only some items.
Key takeaways- arr.map(x => ...)
- Same length
- Original untouched