The map() method of the Array class in JavaScript returns a new array containing the results of invoking a provided function on every element in the calling array.
There are 2 variations for the syntax of Array.map() method. They are:
map(callbackFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to execute on each element in the array. It takes three arguments: element, index, and array. |
This method returns a new array containing the results of invoking a function on every element in the calling array.
Returns value of type Array
.
map(callbackFn, thisArg)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to execute on each element in the array. It takes three arguments: element, index, and array. |
thisArg | optional | A value to use as this when executing callbackFn. |
This method returns a new array containing the results of invoking a function on every element in the calling array, using thisArg as the value of this inside callbackFn.
Returns value of type Array
.
In JavaScript, we can use the map() method to create a new array with the values doubled.
For example,
const arr = [1, 2, 3, 4, 5];
const double = element => element * 2;
const doubledArr = arr.map(double);
console.log(doubledArr);
[2, 4, 6, 8, 10]
We can use the map() method to create a new array with the lengths of the strings in the original array.
For example,
const strArr = ['apple', 'banana', 'cherry'];
const getLength = element => element.length;
const lengths = strArr.map(getLength);
console.log(lengths);
[5, 6, 6]
We can use the map() method with a thisArg to create a new array using a specific context.
For example,
const arr = [1, 2, 3];
const context = { multiplier: 3 };
function multiply(element) {
return element * this.multiplier;
}
const multipliedArr = arr.map(multiply, context);
console.log(multipliedArr);
[3, 6, 9]
In this JavaScript tutorial, we learned about map() method of Array: the syntax and few working examples with output and detailed explanation for each example.