Polyfill for Array.map

JavaScript array has an inbuilt method map() which takes a callback function as input and returns the processed data from this function in a new array.

Example

const arr = [1, 2, 3];
const multipliedArr = arr.map((e) => e * 2);
console.log(multipliedArr);

//[2, 4, 6]

I have checked what arguments this callback takes and found that this callback function takes three arguments, element, index of the element, and the original array itself.

As we can see that in this image.

Javascript array map polyfill

Array.map polyfill

It is extremely common question in JavaScript interviews where it is asked to implement polyfill for the map() method.

A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers

Array.map polyfill should have these two functionalities.

  • The map() function should take an callback function as an argument.
  • Current element, its index, and the context should be passed as an argument to the callback function.
Array.prototype.map = function (callback) {
  //Store the new array
  const result = [];
  for (let i = 0; i < this.length; i++) {
    //cross check if the element is part of the current
    if (this.indexOf(this[i]) > -1) {
      result[i] = callback(this[i], i, this)
    }
  }
  
  //return the array
  return result
}