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
Example
#const numbers = [1, 2, 3, 4]
const doubled = numbers.map((n) => n * 2)
console.log(doubled)
console.log(numbers)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
#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 asthisinsidecallbackFn. It has no effect with arrow functions.
More examples
#const students = [
{ name: 'Emma', points: 120 },
{ name: 'Jack', points: 95 },
{ name: 'Mia', points: 140 }
]
const names = students.map((student) => student.name)
console.log(names)const tasks = ['HTML', 'CSS', 'JavaScript']
const numbered = tasks.map((task, index) => `${index + 1}. ${task}`)
console.log(numbered.join('\n'))console.log(['1', '2', '3'].map(parseInt))
console.log(['1', '2', '3'].map(Number))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 forgottenreturninside curly braces gives an array full ofundefined. - Don’t change the original objects inside
map(). Return new ones instead:{ ...user, active: true }.
Related entries
#- map() vs forEach()map() builds a new array from a function’s results, while forEach() only calls the function for every element and always returns undefined.
- Array.prototype.filter()Creates a new array with the elements for which the function returned true.
- Array.prototype.forEach()Calls a function for every element of the array.
- Array.prototype.reduce()Reduces the whole array to a single value, such as a sum, an object, or a new array.
- Array.prototype.flatMap()Maps every element and flattens the result by one level.
Spotted a mistake or missing an example? Write to us.