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.

  1. The first parameter is which function to apply to each element. This is a required parameter.

  2. 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.

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 unchanged
console.log("Original: ", arr)
console.log("Result: ", result)

Free Resources