The map() method creates a new array with the results of calling a function for every array element.
Example
map() Syntax
The syntax of the map() method is:
arr.map(callback(currentValue), thisArg)
Here, arr is an array.
map() Parameters
The map() method takes in:
- callback - The function called for every array element. Its return values are added to the new array. It takes in:
- currentValue - The current element being passed from the array.
- thisArg (optional) - Value to use as
thiswhen executing callback. By default, it isundefined.
map() Return Value
- Returns a new array with elements as the return values from the
callbackfunction for each element.
Notes:
map()does not change the original array.map()executescallbackonce for each array element in order.map()does not executecallbackfor array elements without values.
Example 1: Mapping array elements using custom function
Output
[ 42.42640687119285, 44.721359549995796, 54.772255750516614, 70.71067811865476, 22.360679774997898, 89.44271909999159 ] [ 'J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't' ] [ 74, 97, 118, 97, 83, 99, 114, 105, 112, 116 ]
Example 2: map() for object elements in array
Output
[
{ name: 'Adam', netEarning: 4500 },
{ name: 'Noah', netEarning: 7000 },
{ name: 'Fabiano', netEarning: 1800 },
{ name: 'Alireza', netEarning: 4600 }
]
Note: map() assigns undefined to the new array if the callback function returns undefined or nothing.
Recommended Reading: JavaScript Array filter()