Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 12, 2022 05:41 am GMT

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

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

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...


Original Link: https://dev.to/mdamirgauhar/polyfills-made-easy-4p89

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To