DEV Community

Sushmitha C
Sushmitha C

Posted on

How to write polyfill for map

Polyfill for map function in JavaScript

JavaScript's map function is widely used for iterating over arrays and applying a transformation to each element. However, if you're working with older browsers or environments that don't support map, you can create your own polyfill.

Image description

Step 1: It is a function : create a normal function with the name 'myMap' as below

Image description

Step 2: This function takes callback function 'callback' as parameter

Image description

Step3: array.map() doesn't affect original array. So create a new array 'output' and return the newly created array.

Image description

Step 4: Map operates on each element of the array. So loop through each element using for loop

Image description

Step 5: When each element of original array is mapped,push the modified value into 'output' array to return it.

Image description

Step 5: The callback function acts on each value of the passed array(this)

Image description

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Unfortunately, this polyfill does not provide all of the functionality of the built-in JS map, and could potentially cause issues if you were to use it. You're missing the optional thisArg parameter.