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
})

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. This example selects words beginning with A and then transforms them:

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 }))

Try it: map a list of cart lines into subtotals, then use reduce() to total them. Confirm the original lines were not mutated.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →