Polyfills in JavaScript are blocks of code that implement functionality not supported in older browsers. Basically it enables the developers to work on latest Javascript/API features in older browsers which do not support them.
map
over an array and we pass a function to process over each element of the array on which the map is called and it returns a new array with mapped element.const arr = [1,2,3,4,5,6] const doubledArray = arr.map((ele) => { return ele*2 }) // doubledArray = [2,4,6,8,10,12]
Array.prototype.compatibleMap = function(func) { let new_array = []; for (let idx = 0; idx < this.length; idx++) { let result = func(this[idx], idx); new_array.push(result); } return new_array }
We named it compatibleMap instead of map to avoid overwriting the native method if it exists.
this
refers to the array on which the map is called, for example arr in example-1 will be referred by this
func
by passing the element and element's index.standard ES6 Map
.const arr = [1,2,3,4,5,6] const doubledArray = arr.compatibleMap((ele) => { return ele*2 }) // doubledArray = [2,4,6,8,10,12]
if (!Array.prototype.map) { Array.prototype.map = function(func) { let new_array = []; for (let idx = 0; idx < this.length; idx++) { let result = func(this[idx], idx); new_array.push(result); } return new_array; } }