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)
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources