Array.prototype.map()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The map() method of Array instances creates
a new array populated with the results of calling a provided function on
every element in the calling array.
Try it
const array = [1, 4, 9, 16];
// Pass a function to map
const mapped = array.map((x) => x * 2);
console.log(mapped);
// Expected output: Array [2, 8, 18, 32]
Syntax
map(callbackFn)
map(callbackFn, thisArg)
Parameters
callbackFn-
A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:
thisArgOptional-
A value to use as
thiswhen executingcallbackFn. See iterative methods.
Return value
A new array with each element being the result of the callback function.
Description
The map() method is an iterative method. It calls a provided callbackFn function once for each element in an array and constructs a new array from the results. Read the iterative methods section for more information about how these methods work in general.
callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.
The map() method is generic. It only expects the this value to have a length property and integer-keyed properties.
Since map builds a new array, calling it without using the returned array is an anti-pattern; use forEach or for...of instead.