Array.prototype.map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
Syntax
// Arrow function
map((element) => { /* ... */ })
map((element, index) => { /* ... */ })
map((element, index, array) => { /* ... */ })
// Callback function
map(callbackFn)
map(callbackFn, thisArg)
// Inline callback function
map(function(element) { /* ... */ })
map(function(element, index) { /* ... */ })
map(function(element, index, array){ /* ... */ })
map(function(element, index, array) { /* ... */ }, thisArg)
Parameters
callbackFn
Function that is called for every element of arr. Each time callbackFn executes, the returned value is added to newArray.
The callbackFn function accepts the following arguments:
element
The current element being processed in the array.
indexOptional
The index of the current element being processed in the array.
arrayOptional
The array map was called upon.
thisArgOptional
Value to use as this when executing callbackFn.
Return value
A new array with each element being the result of the callback function.
Description
map calls a provided callbackFn function once for each element in an array, in order, and constructs a new array from the results. callbackFn is invoked only for indexes of the array which have assigned values (including undefined).
It is not called for missing elements of the array; that is:
indexes that have never been set;
indexes which have been deleted.
When not to use map()
Since map builds a new array, using it when you aren’t using the returned array is an anti-pattern; use forEach or for…of instead.
You shouldn’t be using map if:
you're not using the array it returns; and/or
you're not returning a value from the callback.
Use the share button below if you liked it.
It makes me smile, when I see it.