Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Array.prototype.map()

Reference for JavaScript Array.prototype.map(): transform every element into a new array, callback arguments, the parseInt trap, holes and when to use forEach.

The map() method calls a function once for every element of an array and returns a new array containing the results, in the same order. The original array is not changed, and the new array always has the same length.

Use map() when you want to turn one list into another: prices into formatted strings, users into names, objects into slightly different objects. If you only want side effects such as logging, forEach() or for...of says that more clearly.

JavaScript
const doubled = [1, 2, 3].map((n) => n * 2);
// [2, 4, 6]

Try it

JS Transforming a list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Common traps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
array.map(callbackFn)
array.map(callbackFn, thisArg)
Name Description
callbackFn Called as callbackFn(element, index, array). Its return value becomes the element at the same position in the result.
thisArg Optional. The value used as this inside callbackFn (ignored by arrow functions).

Return value: a new array with the callback's results.

Exceptions: a TypeError if callbackFn is not a function. Errors thrown by the callback propagate and stop the loop.

Usage notes

  • Always returns a new array. The original is untouched, but the elements are not cloned: mapping to the same object, or mutating an object inside the callback, still affects the original objects.
  • Forgetting return with a braced arrow body gives an array of undefined. Use a concise body ((n) => n * 2) or an explicit return. To return an object literal from a concise body, wrap it in parentheses.
  • The parseInt trap. map passes three arguments, so ["1", "2", "3"].map(parseInt) hands the index to parseInt as the radix and gives [1, NaN, NaN]. Wrap the call or use Number.
  • Holes are preserved. Empty slots in a sparse array are skipped and stay empty in the result; the callback is not called for them.
  • The length is fixed at the first call. Elements appended during iteration are not visited; elements changed before they are reached are seen with their new value.
  • Need to filter as well? map() cannot drop elements. Chain filter(), or use flatMap() to return zero or more items per element, or reduce() for full control.
  • Not for side effects. Building and discarding an array just to loop is wasteful and misleading.
  • Async callbacks produce an array of promises. Wrap the result in Promise.all() to wait for them.
  • Generic. It also works on array-likes through Array.prototype.map.call(...), and Array.from(iterable, mapFn) maps while converting.

Browser support

Array.prototype.map() is part of ES5 and works in every browser in use today.