DEV Community

Cover image for Polyfills made easy
Md Amir Gauhar
Md Amir Gauhar

Posted on

Polyfills made easy

Helloo, my fellow developers!!!

Let's talk about Polyfills today. If you are new to this terminology, I'll make sure that this will make complete sense to you.

Let's just begin...
So, a polyfill basically is a piece of javascript code that is used to provide or fill in some functionality that one browser supports but other might not.

Lets make it easy for you to understand by taking an example.
Let us talk about Array.prototype.forEach(). The forEach() method executes a provided function once for each array element.

forEach() calls a provided callbackFn function once for each element in an array in ascending index order.

const arr = [1, 2, 3, 4, 5]
arr.forEach(val => {
  console.log(val * 2)
})

// The above piece of code will take each element of that array/list and will multiply it by 2.
 2
 4
 6
 8
 10
Enter fullscreen mode Exit fullscreen mode

Now lets pretend that we don't have support for forEach().
// Simulate browser incompatibility
Array.prototype.forEach = null
If we try to run the above code again we'll get the following error:

Error

Now let's write a very simple polyfill for forEach() .

if (!Array.prototype.forEach) {

  // polyfill
  Array.prototype.forEach = function (callback) {
    // callback here is the callback function
    // which actual .forEach() function accepts
    for (let value of this)
      callback(value)
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, if we re-run the forEach() method again, it will work perfectly fine.

Lets take a complete look at our code:

polyfill of forEach()

Voilla, we just created a very very rough polyfill for forEach().
Hope you all liked it...

Top comments (0)