AI Hints
Home›JavaScript Tutorial›map, filter, reduce
JavaScript · Lesson 49 of 138

map

Transform every item.

⏱ 2 min read▶ Video at 59:35🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

map
From the video: map
  • 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.

app.jsjavascript
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);
Output
[ 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.

keyvalue
map(fn)new array, same length
fn(item, index)called for each
Originalunchanged
Replacesloop + 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.

app.jsjavascript
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);
Output
[ 'Tea: $3.00', 'Cake: $4.50' ]
{ name: 'Cake', price: 5.4 } 4.5

Summary

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
Next up: filter — keep some items