What is the map() method?

map() creates a new array by calling a function on every element of the original array and collecting the return values; the original array is not changed and the new array always has the same length.

Signature

array.map((element, index, array) => newValue, thisArg?)

When to use it

Whenever you want to transform each item into something else: format prices, pick fields from objects, convert API data into view models, or render a list of React elements.

Rules that trip people up

  • Always return a value. With curly braces you need an explicit return; forgetting it gives an array of undefined.
  • Do not use map for side effects only. If you are not using the result, use forEach or for...of. Linters flag unused map results.
  • Returning an object literal from an arrow needs parentheses: items.map(i => ({ id: i.id })).
  • map with parseInt is a classic trap: ["1", "2", "3"].map(parseInt) gives [1, NaN, NaN] because map passes the index as parseInt's radix. Use map(Number) or an explicit arrow.
  • Async callbacks return promises, so map(async ...) gives an array of promises. Wrap it in Promise.all.

Related

flatMap maps and flattens one level, useful when each item produces zero or many results. Array.from(iterable, mapFn) maps while converting.

Code example

js
1const products = [
2 { id: 1, name: "Laptop", price: 1200 },
3 { id: 2, name: "Mouse", price: 25 },
4];
5
6const labels = products.map((p) => `${p.name}: $${p.price}`);
7console.log(labels); // ["Laptop: $1200", "Mouse: $25"]
8
9const withTax = products.map((p) => ({ ...p, price: +(p.price * 1.2).toFixed(2) }));
10console.log(withTax[1].price, products[1].price); // 30 25 - original untouched
11
12console.log(["1", "2", "3"].map(parseInt)); // [1, NaN, NaN] - index used as radix
13console.log(["1", "2", "3"].map(Number)); // [1, 2, 3]
14
15// flatMap: each item can become 0..n items
16const tags = [{ tags: ["js", "ts"] }, { tags: [] }, { tags: ["css"] }];
17console.log(tags.flatMap((t) => t.tags)); // ["js", "ts", "css"]
18
19// Async map needs Promise.all
20const fetchPrice = async (id) => id * 10;
21const prices = await Promise.all(products.map((p) => fetchPrice(p.id)));
22console.log(prices); // [10, 20]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app