Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

What is the Array map() function in JavaScript?

Fatima Hasan

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)

RELATED TAGS

javascript
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring