This content originally appeared on DEV Community and was authored by Md Amir Gauhar
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:
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:
Voilla, we just created a very very rough polyfill for forEach().
Hope you all liked it...
This content originally appeared on DEV Community and was authored by Md Amir Gauhar
Md Amir Gauhar | Sciencx (2022-01-12T05:41:20+00:00) Polyfills made easy. Retrieved from https://www.scien.cx/2022/01/12/polyfills-made-easy/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.