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.
const doubled = [1, 2, 3].map((n) => n * 2); // [2, 4, 6]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
returnwith a braced arrow body gives an array ofundefined. Use a concise body ((n) => n * 2) or an explicitreturn. To return an object literal from a concise body, wrap it in parentheses. - The
parseInttrap.mappasses three arguments, so["1", "2", "3"].map(parseInt)hands the index toparseIntas the radix and gives[1, NaN, NaN]. Wrap the call or useNumber. - 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. Chainfilter(), or useflatMap()to return zero or more items per element, orreduce()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(...), andArray.from(iterable, mapFn)maps while converting.
Browser support
Array.prototype.map() is part of ES5 and works in every browser in use today.