Skip to main content

map

The map() method iterate over the elements of the array and creates a new array for every array element based on the results of the callback function.

Syntax

// Using Arrow function
map((element) => { /* … */ })
map((element, index) => { /* … */ })
map((element, index, array) => { /* … */ })

// Using Callback function
map(callbackFn)
map(callbackFn, thisArg)

// Using Inline callback function
map(function(element) { /* … */ })
map(function(element, index) { /* … */ })
map(function(element, index, array){ /* … */ })
map(function(element, index, array) { /* … */ }, thisArg)

Parameters

callBack function

At each execution of the callback function, the returned value is added to the new array.

The callBack function have following arguments

  • element: The current element being processed.

  • index: The index of the current element being processed.

  • array: The array at which map is called upon.

  • thisArg: The value to be used as this when calling the callback function.

Additionally, map() provides an optional second parameter in order to set the value of this in the mapping function. Depending on the execution environment, the default value of this might vary:

In a browser, the default value of this is always window:

['one', 'two'].map(function(value, index, arr) { 
console.log(this); // window (the default value in browsers)
return value.length;
});

You can change it to any custom object like this:

['one', 'two'].map(function(value, index, arr) { 
console.log(this); // Object { documentation: "randomObject" }
return value.length;
}, {
documentation: 'randomObject'
});

Examples

Using with array

const array = [1, 4, 9];
const square = array.map((item) => item * item);
console.log(square);
// square is now [1, 16, 81]
// array is still [1, 4, 9]

The given example is find the square of the given number. After computation the value is returned and added to the array square.

Using with object

const object = [
{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 }
];
let result = object.map(({key, value}) => ({[key]: value}));
console.log(result);

In this example, key and value are obtained directly using object destructuring by {key, value}. After destructuring, we will get key and value separate from the object which is returned to the array result and consoled.

note

You should not use map if:

  • You're not making use of the array it returns.
  • You're not returning a value from the callback function.