Implement Array.map() in JS

Maayan Savir
2 min readApr 30, 2021
Photo by JOSHUA COLEMAN on Unsplash

In a nutshell

map() is a built-in function of Array in JavaScript. It helps us iterate on an array, calls a provided callback() on each element, and returns a new array with the new results.

Parameters

map() accepts as parameters
- current element — The current element being processed in the array.
- the current element index — The index of the current element being processed in the array.*Optional
- the original array — The array map was called upon.*Optional
- thisArgs — Value to use as this when executing callback.*Optional

Return Value

map() returns a new array where each of the elements is the result of the callback function. Since map() returns a new array, it doesn’t modify the existing one.

In Details

  • callback is invoked with three arguments: the value of the element, the index of the element, and the array object being mapped
  • If a thisArg parameter is provided, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value
  • map does not mutate the array on which it is called (although callback, if invoked, may do so).
  • It is not called for missing elements of the array -
    indexes that have never been set;
    indexes that have been deleted
  • if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank

Implementation

With all the information we know on the map() method, we can implement our custom map() function.

Conclusion

map() is not a complex function to implement but it can be very tricky. Just need to keep in mind the needs and limitations it has.

--

--