Objects

The JavaScript map() Function

Learn how to use the JavaScript array map() method to build a new array by running a function on every element, then chain it with filter() to refine results.

map() builds a new array with one output for every input. The original array length and order are preserved.

This example calls f for each element:

const b = a.map(f)

Use it when each input becomes a corresponding output:

const prices = [10, 20, 30]
const pricesWithTax = prices.map(price => price * 1.2)

The callback’s return value becomes the new element. Forgetting return in a block callback produces undefined values:

const doubled = prices.map(price => {
  return price * 2
})

Run prices.map(p => p * 2) and compare the new array to prices. The original stays unchanged.

Do not use map() only for side effects. If you are not using the returned array, forEach() or a loop communicates the intent better.

Chain operations when the intermediate meaning stays clear:

const list = ['Apple', 'Orange', 'Apricot']
const labels = list
  .filter(item => item.startsWith('A'))
  .map(item => item.toUpperCase())

map() is shallow. If a callback mutates an object, that same object is changed in the source array. Return a new object when immutability matters:

const activeUsers = users.map(user => ({ ...user, active: true }))

The callback receives three arguments: the element, its index, and the original array. Most code only uses the first.

const labels = ['a', 'b', 'c'].map((item, index) => `${index}: ${item}`)
console.log(labels) // ['0: a', '1: b', '2: c']

map() always returns a new array with the same length. If some inputs should be dropped, use filter() first or switch to flatMap() when each input can produce zero or many outputs.

You can map over array-like values after converting them:

const letters = Array.from('hey').map(char => char.toUpperCase())
console.log(letters) // ['H', 'E', 'Y']

Async code sometimes uses Promise.all(items.map(item => fetch(item))) to run independent requests in parallel. That is still map(), just with promises as the mapped values.

If the callback returns nothing in a block body, you get an array of undefined values. That bug shows up in code reviews more often than you would expect.

Map cart lines { qty: 2, price: 10 } into subtotals, then reduce to one total. Confirm the original lines were not mutated.

Lesson completed