DEV Community

Gurmeet Singh
Gurmeet Singh

Posted on

Polyfill for map in javascript

The map() method in JavaScript is used to iterate over an array and apply a function to each element in the array, returning a new array with the results. For those who are new to javascript here is a basic example of how map() works

// Define an array of numbers
const numbers = [1, 2, 3, 4, 5];

// Use the map() method to square each number in the array
const squaredNumbers = numbers.map(function(number) {
  return number * number;
});

// Output the new array of squared numbers
console.log(squaredNumbers); // [1, 4, 9, 16, 25]

Enter fullscreen mode Exit fullscreen mode

For an indepth understanding of map() please refer this link

As seen above map() is a very useful method, but not all browsers support it. In this blog post, we will create a polyfill for the map() method so that it can be used in all browsers.

Here's the code for the map() polyfill -

if (!Array.prototype.map) {
  Array.prototype.map = function(callback, thisArg) {
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    var newArray = [];

    for (let i = 0; i < this.length; i++) {
      if (this.hasOwnProperty(i)) {
        newArray[i] = callback.call(thisArg, this[i], i, this);
      }
    }

    return newArray;
  };
}
Enter fullscreen mode Exit fullscreen mode

Let's break down this code -

  1. First, we check if the map() method already exists on the Array prototype. If it does not exist, we create our implementation.
  2. We define the map() function on the Array prototype, taking two arguments: a callbackfunction and an optional thisArg parameter.
  3. We check if the callbackargument is a function, and throw a TypeError if it is not.
  4. We create a new empty array to hold the results of the mapping operation.
  5. We iterate over each element in the array, using the hasOwnProperty() method to skip any non-existent elements such as properties added to the array's prototype.
  6. For each element, we call the callback function with the element, the index, and the original array as arguments, using the call() method to set the this value to thisArg if it is provided.
  7. We store the result of the callback function in the new array.
  8. We return the new array containing the mapped results.

And that's it! With this map() polyfill, you can use the map() method on arrays in all browsers, even if they do not support it natively.

Top comments (1)

Collapse
 
okayhead profile image
Shashwat jaiswal

I have one question. Why did you use var to store the new array?

 var newArray = [];
Enter fullscreen mode Exit fullscreen mode