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.
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 this
keyword. If it is not provided, this
should not be used.
array.map(function(currentValue, index, arr), valueForThis)
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.
function(...)
A new array is returned with the given function that is applied to each element.
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)