Polyfills

Polyfills

Table of contents

No heading

No headings in the article.

What are exactly polyfills?

New built in functions or new syntaxes in javascript, they might not work in outdated browsers. Some javascript engines might not be supporting them. To solve this problem, polyfills comes into the picture.

Pollyfill is like a code snippet that helps browser to support javascript new or native functions as well as new syntaxes to work properly.

Lets discuss a very simple example.

Lets say in some outdated browsers Array.filter function is not working. So lets create a polyfill of filter function which will work in all the browsers which does not support filter function

Example Code:

    Array.prototype.filter = function (callbackFn) {
      let outputArr = [];

      this.forEach((el, index) => {
        if (callbackFn(el, index, this)) {
          outputArr.push(el);
      }
    });

    return outputArr;
  };

  console.log([1, 2, 4, 5, 6, 7].filter((el) => el % 2 == 0));

So in the above example, I am creating a polyfill of filter function. I am replacing the filter function present in prototype of Array with my own polyfill function which is doing following:

  1. Creating a new array
  2. Looping over the existing array and checking whether the condition is true or not. If condition is true, we are putting the elements in new array
  3. Lastly we will return the array

In this way polyfill can be created.

Lets discuss one more example. Lets create a polyfill of map function

Example Code:

  Array.prototype.map = function (callbackFn) {
    let outputArr = [];

    this.forEach((element, index) => {
      outputArr.push(callbackFn(element, index, this));
    });

    return outputArr;
  };

  console.log([1, 2, 3, 4].map((e) => 10 * e));

Its almost similar to the first example. Only difference is we are not checking conditions. We are executing the callbackFn on every element and pushing the result of callback function in the new array that we will return.

So, I hope now you understand what are polyfills and how to create one. There are other examples of polyfill as well. For every existing function in javascript you can make a polyfill to make older or outdated browsers to support them.

Thank you all. Regards, Yatharth