Polyfills in JavaScript. kids wait for browser's update, legends make their own polyfill.

Polyfills in JavaScript. kids wait for browser's update, legends make their own polyfill.

In the web world, technologies and functionalities are getting updated rapidly. But that doesn't necessarily mean that our browser is ready to serve us every new functionality. But one doesn't have to sacrifice using the latest features in your application, to make it run on every browser.

Because we have "Polyfills"!

Polyfills are a piece of code, that mimics a particular functionality that might not be supported by a browser, you want to run your application on.

This piece of code can be a mimic of many types of technology.

  • Maybe some HTML that isn't supported (like canvas), or
  • maybe some Javascript method (like find() method).

Simple polyfill for array.map() function

Let's take an example. Suppose your browser doesn't support the array's map() method. Now, what will you do? Of course, you'll create a polyfill here.

  • Simply create a function that takes an array as an argument, and also takes another function as an argument.
const mapPolyfill = (arr,callback) => {

}
  • Now within this polyfill, you will iterate through every element of that array, and run the function you took as an argument, on each and every element.
const mapPolyfill = (arr,callback) => {
     for (var i = 0; i < arr.length; i++) {
         callback(arr[i]);
      }
}
  • Now push these new elements in a new array, and return this updated array. You have just created your own polyfill!
const mapPolyfill = (arr,callback) => {
   var newArr = [];
   for (var i = 0; i < arr.length; i++) {
      newArr.push(callback(arr[i], i, arr)) // pushing currentValue, index, array
    }
}

let arr = [1,2,3]

mapPolyfill( arr, (val) => val*val ) // will return an array [1,3,9]
  • At last, to make this polyfill work on any array, you can add this polyfill function to the Array's prototype (a prototype is an object that contains all the properties and method of a constructor function, in this case, Array). [ But first, you have to make some changes in the polyfill]
const mapPolyfill = (callback) => {
   var newArr = [];
   for (var i = 0; i < this.length; i++) {
      newArr.push(callback(this[i], i, this)) // pushing currentValue, index, array
    }
}

Array.prototype.ourMap = mapPolyfill;

Want to learn this concept with more clarity and real-world example? Check out this amazing article by Anurag Majumdar on the same.

Happy coding :)

#10daysofJSfundamentals (DAY 9)