Polyfills

Definition/Purpose

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.

Example

ES6 Map

Example-1

const arr = [1,2,3,4,5,6] const doubledArray = arr.map((ele) => { return ele*2 }) // doubledArray = [2,4,6,8,10,12]

ES6 Map Polyfill

Example-2

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.

Example-3

const arr = [1,2,3,4,5,6] const doubledArray = arr.compatibleMap((ele) => { return ele*2 }) // doubledArray = [2,4,6,8,10,12]

Complete Example

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; } }