map()

ES5+

Creates a new array with the results of calling a provided function on every element in the calling array.

Syntax

array.map(callback(element, index, array), thisArg)

Parameters

callback Function

Function that produces an element of the new Array

thisArg any optional

Value to use as this when executing callback

Return Value

Array

A new array with each element being the result of the callback function

Examples

JavaScript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(x => x * 2);
console.log(doubled);
Output:
// [2, 4, 6, 8]

📌 When to Use

Use map() when you need to transform each element in an array into something new. It's ideal for data transformation pipelines where you want to convert data formats, extract specific properties, or apply calculations to every item.

⚠️ Common Mistakes

Using map() when you don't need the returned array - use forEach() instead for side effects only

Forgetting that map() always returns an array of the same length as the original

Accidentally returning undefined by forgetting the return statement in multi-line callbacks

✅ Best Practices

Keep callback functions pure - avoid modifying external state or the original array

Chain map() with filter() for clean data transformations: filter first, then map

Use arrow functions for concise single-expression transforms: arr.map(x => x * 2)

⚡ Performance Notes

map() creates a new array, so for very large arrays, consider if you really need transformation or if a simple loop would be more memory-efficient. For chained operations, consider using a single reduce() instead of map().filter().map() chains.

🌍 Real World Example

Converting API Response to Display Format

Transform user data from an API into a format suitable for a dropdown menu

// API returns: [{id: 1, firstName: 'John', lastName: 'Doe'}, ...]
const users = await fetchUsers();
const dropdownOptions = users.map(user => ({
  value: user.id,
  label: `${user.firstName} ${user.lastName}`
}));
// Result: [{value: 1, label: 'John Doe'}, ...]

Related Methods