Skip to content

Array Map Method

map() calls a function on each element of an array and returns a new array of the results, in the same order. The new array always has the same length as the original, and the original is left unchanged. Use it whenever you want one value out for each value in, such as prices with tax added, or names taken from a list of records.

const prices = [10, 25, 4.99];
const withVat = prices.map((price) => Math.round(price * 1.2 * 100) / 100);
console.log(withVat);
console.log(prices);

This prints:

[ 12, 30, 5.99 ]
[ 10, 25, 4.99 ]

The callback must return a value. If it returns nothing, the new array is filled with undefined.

map() is often used to pull one property out of each object, or to build a smaller object from each one. An arrow function that returns an object literal needs the literal wrapped in brackets, because otherwise JavaScript reads the braces as the function’s body.

const books = [
{ title: 'Middlemarch', author: 'George Eliot', pages: 880 },
{ title: 'Persuasion', author: 'Jane Austen', pages: 249 },
{ title: 'Bleak House', author: 'Charles Dickens', pages: 1017 },
];
const titles = books.map((book) => book.title);
const sizes = books.map((book) => ({ title: book.title, long: book.pages > 500 }));
console.log(titles);
console.log(sizes);

This prints:

[ 'Middlemarch', 'Persuasion', 'Bleak House' ]
[
{ title: 'Middlemarch', long: true },
{ title: 'Persuasion', long: false },
{ title: 'Bleak House', long: true }
]

Like forEach(), map() passes the callback the element, its index and the whole array. This matters when you pass an existing function straight to map(), because that function receives all three arguments whether it expects them or not. parseInt() takes a radix as its second argument, so it gets the index there and fails:

const quantities = ['1', '2', '3'];
console.log(quantities.map(parseInt));
console.log(quantities.map(Number));
console.log(quantities.map((text) => parseInt(text, 10)));

This prints:

[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]

Number ignores the extra arguments, so it is safe to pass directly. With any other function, wrapping it in an arrow function that passes only the element avoids the problem.

Steve Griffith covers this topic in his video JavaScript Array map method.