What is the Array map() function in JavaScript?
The map() method takes a function as a parameter, applies that function to every element in the array, and returns a new array with the results.
Parameters of map()
map() takes two arguments at most.
-
The first parameter is which function to apply to each element. This is a required parameter.
-
The second parameter is optional and is provided with the function to be used as the
thiskeyword. If it is not provided,thisshould not be used.
Syntax
array.map(function(currentValue, index, arr), valueForThis)
Parameters of function(...)
The function to be provided as input takes the following three parameters at most.
-
currentValue: This is the only required one. It contains the value of the current element of the array. -
index: This contains the index of the current element. -
arr: This contains the array on which the map() function is applied.
Return value of function(...)
A new array is returned with the given function that is applied to each element.
Code
function doubleArray(x){return x*2;}arr = [1, 2, 3, 4, 5]result = arr.map(doubleArray)//The original array is unchangedconsole.log("Original: ", arr)console.log("Result: ", result)