Polyfill for map in javascript
Gurmeet Singh
Posted on March 5, 2023
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]
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;
};
}
Let's break down this code -
- First, we check if the
map()
method already exists on theArray prototype
. If it does not exist, we create our implementation. - We define the
map()
function on theArray prototype
, taking two arguments: acallback
function and an optionalthisArg
parameter. - We check if the
callback
argument is a function, andthrow
aTypeError
if it is not. - We create a new empty array to hold the results of the mapping operation.
- 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. - 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 thethis
value tothisArg
if it is provided. - We store the result of the callback function in the new array.
- 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.
Posted on March 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.