Polyfills in javascript

Polyfills in javascript

What exactly is Polyfill ?

Polyfill is a piece of javascript code that is used to provide or fill in some functionality that one browser might support but another browser might not support.

Let's take an example of arrow functions, they are basically shorthand for functions but you may not know that all browsers don't necessarily support arrow functions.

If you refer to MDN DOC for arrow function in the browser compatibility section you can see that arrow functions are largely supported by most browsers except for internet explorer does not natively support arrow functions

image.png

In Such above cases, a developer might write a piece of polyfill code in order to fill the gap here for ie so it won't be the original arrow function implementation but it'll be a piece of code that can basically simulate the arrow functions behavior in order for ie to support it and to understand it

image.png

how to check your polyfill code is working or not ?

Array.prototype.map = null;

In this way, you can disable the method in your current browser to check your polyfill code is working or not !

keep one thing in mind whenever you need to write polyfill code firstly you need check for that resp method in your browser is present or not like this,

if(!Array.prototype.map)
{
       //your polyfill code
}

so now that we kind of got an idea of what a polyfill is let's go and write our own polyfill code for the map method

carbon.png

In the above example,

  • we are temporarily disabling the map method

  • we are checking for that resp. method if it is present in our browser or not

  • wrote our polyfill code

as in our original code, we are passing a callback function to map method so in polyfill code we are passing a normal function with for loop which will iterate over a given array and will return the expected output.

So guys this is a short introduction to Polyfill in JavaScript. I hope you got some knowledge through this blog.

Thank You ! I'll see you in the next blog

Have a nice day! ๐Ÿ˜‰

ย