“map” function in JavaScript


“map” function is defined on the prototype of “Array” class in JavaScript and is one of the commonly used functions.

Array.prototype.map

It returns a new array containing the return value from a callback function executed on each element of the array on which it was called.

Syntax

map(callbackFn, thisArg)
  • callbackFn – Callback function which is to be executed on the elements of the original array.
    • callbackFn(element, index, array)
      • element – Current element of the array on which this function is getting called.
      • index – Optional – Index of the current element in the array.
      • array – Optional – Array on which the “map” is called.
  • thisArg – Optional – Value to be used as “this” when calling the callback function.

Examples

    const numbers = [1, 2, 3, 4, 5, 6];
    const cubes = numbers.map(x => Math.pow(x, 3));
    console.log(cubes);
[ 1, 8, 27, 64, 125, 216 ]
    const friends = ["John", "Brad", "Mike", "Ashutosh"];
    const friendsDetails = friends.map((x, i) => {
        return { name: x, charCount: x.length, positionInList: i };
    });
    console.log(friendsDetails);
[
  { name: 'John', charCount: 4, positionInList: 0 },
  { name: 'Brad', charCount: 4, positionInList: 1 },
  { name: 'Mike', charCount: 4, positionInList: 2 },
  { name: 'Ashutosh', charCount: 8, positionInList: 3 }
]

Can we write our own “map” function?

Yes, it is possible to write our own “map” function. In earlier times, developers often include polyfills with their web applications to provide an implementation of such methods which were not supported by the browsers at that time. Let’s try to write a very simple polyfill for “map” function.

    Array.prototype.myMap = function (callbackFn, thisArg) {
        const newArray = new Array(this.length);

        for (let i = 0; i < this.length; i++) {
            const result = callbackFn.call(thisArg, this[i], i, this);
            newArray[i] = result;
        }

        return newArray;
    }

Let’s try our implementation with an example and see if it works.

    const colors = ['Red', 'Yellow', 'Green', 'Blue', 'Purple', 'Grey'];
    const upperCaseColors = colors.myMap(x => x.toUpperCase());
    console.log(upperCaseColors);
[ 'RED', 'YELLOW', 'GREEN', 'BLUE', 'PURPLE', 'GREY' ]

Explanation

Let us understand the above code step by step.

  1. Define a new function on prototype of Array class. We are doing this because we want our function to be available on arrays rather taking them as argument.
  2. Create a new array of the same length on which this function is called upon.
  3. Iterate on the original array, calling the callbackFn with each element as argument and assigning the result to the same index in the new array.
  4. Return the new array.

References

  1. Mozilla Developer Network (MDN)