The JavaScript map() Function

By

Published · Updated

Tagged: JavaScript

Learn how JavaScript array map() builds a new array from each element, when not to use it, and how a missing return fills the result with undefined.

map() walks an array and builds a new array. Each item in the original becomes one item in the result.

This example iterates a and builds a new array with the result of executing f() on each a element:

const b = a.map(f)

map() never mutates the original array. It returns a new array of the same length.

Here is a concrete case. We have prices, and we want each one with 20% tax:

const prices = [10, 20, 30]
const withTax = prices.map(price => price * 1.2)
// [12, 24, 36]

prices is still [10, 20, 30].

The function you pass gets three arguments: the element, its index, and the whole array. Most of the time you only need the first one.

const cities = ['Rome', 'Milan', 'Florence']
cities.map((city, index) => `${index + 1}. ${city}`)
// ['1. Rome', '2. Milan', '3. Florence']

A missing return

Be careful with a block body. If you open { } you must return a value. Forget the return and every slot becomes undefined:

prices.map(price => {
  price * 1.2
})
// [undefined, undefined, undefined]

The arrow form without braces already returns the expression, so that one is fine.

When not to use map()

map() is the wrong tool when you don’t need the new array. If you just want to log items, or change something on the side, use a for...of loop or forEach().

Another trap: passing parseInt directly. map() calls your function with (element, index, array). parseInt treats that second argument as the radix:

['1', '2', '3'].map(parseInt)
// [1, NaN, NaN]

Wrap it so you only pass the string, and set the radix yourself:

['1', '2', '3'].map(value => parseInt(value, 10))
// [1, 2, 3]

map() also skips empty slots in a sparse array. The hole stays a hole in the result. An undefined value is visited. Those are not the same thing.

Chaining with filter()

You can chain map() with filter(). This example takes the first letter of each item, then keeps the one that matches A:

const list = ['Apple', 'Orange', 'Egg']
list.map(item => item[0]).filter(item => item === 'A') //['A']

filter() always returns an array. I also have posts on filter() and reduce().

Want me to talk about your product? You can sponsor this site.

Related posts about js: