jsguides

Array.prototype.map()

map(callbackFn, thisArg?)

map() creates a new array populated with the results of calling a callback on every element in the calling array. It transforms data by applying a function to each item, making it one of the most commonly used array methods in JavaScript.

Syntax

map(callbackFn)
map(callbackFn, thisArg)

Parameters

ParameterTypeDefaultDescription
callbackFnFunctionFunction called for each element, returning a new value
thisArganyundefinedValue to use as this when executing callbackFn

The callback function receives three arguments:

ArgumentTypeDescription
elementanyCurrent element being processed
indexnumberIndex of current element
arrayArrayArray that map was called upon

Examples

Basic usage

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled);
// [2, 4, 6, 8, 10]

The callback receives each element and its return value populates the new array at the same position. This simple transform shows the core idea, but map is most useful when you apply it to collections of objects, extracting or reshaping data in a single pass.

Transforming objects

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const names = users.map(user => user.name);
console.log(names);
// ['Alice', 'Bob', 'Charlie']

Beyond extracting properties, you can also access the index of each element as the second callback argument. This is useful when you need to number items, create compound keys, or decorate each element with its position in the original array.

Using index parameter

const fruits = ['apple', 'banana', 'cherry'];
const indexed = fruits.map((fruit, i) => `${i + 1}. ${fruit}`);
console.log(indexed);
// ['1. apple', '2. banana', '3. cherry']

Because map returns an array, it chains naturally with other array methods like filter, reduce, and sort. By filtering before you map, you avoid running the callback on elements you plan to discard, keeping each step focused on a single concern.

Common Patterns

Chaining with other array methods

const numbers = [1, 2, 3, 4, 5];

const result = numbers
  .filter(n => n > 2)
  .map(n => n * 10);
  
console.log(result);
// [30, 40, 50]

Extracting a single property is the most common map pattern in production code. This turns a collection of structured data into a flat list that feeds directly into rendering, aggregation, or further pipeline transformations without the overhead of a for loop.

Extracting specific properties

const products = [
  { id: 1, price: 100, name: 'Widget' },
  { id: 2, price: 200, name: 'Gadget' }
];

const prices = products.map(p => p.price);
console.log(prices);
// [100, 200]

The opposite direction—building objects from flat data—is equally common. When the callback returns an object literal, wrap it in parentheses so the parser does not treat the curly brace as a function body. Forgetting the parens is a frequent mistake that produces undefined instead of an object.

Creating objects from arrays

const ids = [1, 2, 3];
const objects = ids.map(id => ({ id, status: 'active' }));
console.log(objects);
// [{ id: 1, status: 'active' }, { id: 2, status: 'active' }, { id: 3, status: 'active' }]

Key Behaviors

  • map() does not mutate the original array
  • map() returns a new array with the same length as the original
  • map() skips holes in sparse arrays but preserves them
  • map() always returns a new array—even if all elements remain unchanged

map() vs forEach()

map() and forEach() both iterate every element and call a callback, but they serve different purposes. map() builds and returns a new array from the callback’s return values. forEach() returns undefined and is only useful for side effects. If you are not using the returned array, use forEach() instead of map() — calling map() and discarding the result wastes memory by creating an array that is immediately thrown away. Conversely, if you need the transformed values, prefer map() over forEach() with a manual push, since map() expresses the intent more clearly and avoids external state.

map() and sparse arrays

map() preserves holes in sparse arrays — it skips them (does not call the callback) but preserves the gaps in the output. The result has the same indices and length as the original. This differs from filter(), which always produces a dense array with no holes.

const sparse = [1, , 3];
sparse.map(x => x * 2); // [2, empty, 6]

Return value considerations

The callback should return a value on every code path. If the callback returns undefined for some elements (for example, a function with no explicit return), those positions in the output array will be undefined. This is a common source of bugs when converting an existing function to use as a map() callback — verify that it always returns the expected value.

See Also