JavaScriptArrays

Array.prototype.map()

Creates a new array with the results of calling a function for every element.

Returns
A new array with the function’s results, the same length as the original.
Changes the original
No
On this page

Example

#
JavaScript
const numbers = [1, 2, 3, 4]
const doubled = numbers.map((n) => n * 2)

console.log(doubled)
console.log(numbers)
Console
[2, 4, 6, 8]
[1, 2, 3, 4]

Definition and usage

#

The map() method walks through the array’s elements in order, calls the given function for each one, and builds a new array of the same length from the results. The original array is left untouched.

It’s the basic tool for transforming data: turning prices into prices with tax, user objects into plain names, or API data into list items in the UI.

If you don’t need a new array and just want to do something with each element (like logging it to the console), use forEach() instead. Using map() without using its result is a common mistake.

Syntax

#
Syntax
array.map(callbackFn)
array.map(callbackFn, thisArg)

Parameters

#
  • callbackFn

    function (element, index, array)

    The function called for every element. It receives the current element, its index, and the whole array. Whatever it returns ends up in the new array.
  • thisArg

    optional

    The value used as this inside callbackFn. It has no effect with arrow functions.

More examples

#
Plucking one field from objects
JavaScript
const students = [
  { name: 'Emma', points: 120 },
  { name: 'Jack', points: 95 },
  { name: 'Mia', points: 140 }
]

const names = students.map((student) => student.name)
console.log(names)
Console
['Emma', 'Jack', 'Mia']
Using the index
JavaScript
const tasks = ['HTML', 'CSS', 'JavaScript']
const numbered = tasks.map((task, index) => `${index + 1}. ${task}`)

console.log(numbered.join('\n'))
Console
1. HTML
2. CSS
3. JavaScript
Pitfall: parseInt as a function
JavaScript
console.log(['1', '2', '3'].map(parseInt))
console.log(['1', '2', '3'].map(Number))
Console
[1, NaN, NaN]
[1, 2, 3]

map() also passes the index to the function, and parseInt treats the second argument as the numeral system’s base. Hence the NaN. It’s safer to use Number or (s) => parseInt(s, 10).

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • The function passed to map() should return a value. A forgotten return inside curly braces gives an array full of undefined.
  • Don’t change the original objects inside map(). Return new ones instead: { ...user, active: true }.

Related entries

#

Spotted a mistake or missing an example? Write to us.