Polyfills - Bridging Gaps in JavaScript

Polyfills - Bridging Gaps in JavaScript

Writing Your Own Polyfills - Step by Step

What is Polyfills ?

Polyfill is a way to modify or add new functions. It is basically a piece of code to add/modify the new functions. It is used to provide modern functionality to web browsers.

Why we Use ?

Polyfills in the javaScript that adds modern features to the older browser which does’t support them and also you can add your own features as well .

Basically polyfill address the gap support in browser for the modern features of javascript.It ensures that the modern javascript code run in the older browser.

Polyfills add missing features, such as ES6+ syntax and built-in functions, to environments lacking support.

Polyfills are like add-ons that help old browsers understand new JavaScript features. When used with tools like Babel, they make sure modern code runs smoothly on older browsers.

How Polyfills Work?

Polyfills check if a feature is supported in the current browser. If it isn’t, they add their own implementation.

It’s like browser fallback what if your browser doesn’t provide the map( ) function then you will need to code your own map( ) function. We will discuss polyfills for the following methods:

  • Using map( )

  • Using forEach( )

  • Using reduce( )

  • Using filter( )

  • Using includes( )

if(!Array.prototype.fill){
    //Fallback - polyfill - backup function
    Array.function()
}

Step by Step to create polyfill

Step 1 : Understand the Feature You Want to Polyfill

Firstly you need to Read the official specification and also before writing a polyfill, you need to Check if the feature is natively available using typeof or in.

  • Now i am goining to create my own .map method named as myMap

Step 2 : Check for Native Support

Before writing your polyfill, ensure the feature doesn’t already exist to avoid overriding built-in implementations.

if (!Array.prototype.myMap) {
  // Add polyfill here
}

Step 3: Implement the Polyfill

Example 1: Array.prototype.myMap

const n = arr.myMap(function(value,index){
    return 2*value;
})

Polyfill of myMap

if(!Array.prototype.myMap){
    Array.prototype.myMap = function(userFn){
        const result = []

        for(let i=0;i<this.length ;i++){
           const value =  userFn(this[i],i);
           result.push(value)
        }
        return result;
    };
}

Step 4: Test the Polyfill

After writing your polyfill:

  • Test it in modern browsers to compare results.

  • Test it in older browsers where the feature is missing.

const arr = [1, 2, 3];
const doubled = arr.myMap(value =>value * 2);
console.log(doubled); //  output: [2, 4, 6]

Step 5: Optimize and Avoid Conflicts

  • Wrap your polyfill inside an IIFE (Immediately Invoked Function Expression) to avoid polluting the global scope.
  • Use feature detection (if (!feature)) before defining a polyfill.

  • Ensure the polyfill follows the ECMAScript specification closely.

Lets See some more example:

1.Create own .filter

  • I am going to write own filter polyfill named myFilter.

    Array.prototype.myFilter

Polyfill :

if(!Array.prototype.myFilter){
    Array.prototype.myFilter = function(userFn){
        const result =[]

        for(let i=0;i<this.length;i++){
            if(userFn(this[i])){
                result.push(this[i]);
            }
        }
        return result;
    }
}
const arr = [1,2,3,4,5,6]
const n3= arr.myFilter((e)=>e%2 == 0);
console.log(n3)// output: [2, 4, 6]

2.Create own forEach

  1. I am going to write own filter polyfill named myForEach.

    Array.prototype.myForEach

Polyfill :

if(!Array.prototype.myForEach){
    Array.prototype.myForEach = function(userFn){
        const originalArr = this// Doubt - depend on context - current object ki taraf point karta hai

        for(let i=0;i<originalArr.length;i++){
            userFn(originalArr[i],i);
        } 
    }
}
const arr = [1,2,3,4,5,6]
const ret = arr.myForEach(function(value,index){
    console.log(`My for Each value at index ${index} is ${value}`);
});
//Output:
//My forEach value at index 0 is 1
//My forEach value at index 1 is 2
//My forEach value at index 2 is 3
//My forEach value at index 3 is 4
//My forEach value at index 4 is 5
//My forEach value at index 5 is 6

3.Create Polyfills for includes( ) function

Array.prototype.includes

Polyfill:

if (!Array.prototype.includes) {
  Array.prototype.includes = function (searchElement, fromIndex) {
    let arr = this;
    let len = arr.length;

    if (len === 0) return false;

    let start = fromIndex || 0;
    if (start < 0) start = Math.max(0, len + start);

    for (let i = start; i < len; i++) {
      if (arr[i] === searchElement) return true;
    }

    return false;
  };
}
console.log([1, 2, 3].includes(2)); // Should return true

4. Polyfill for reduce( ) function

  • Reduce function - Find the sum of all the even numbers inside the given array.

Array.prototype.reduce


Array.prototype.myReduce = function (callback, sum) { 
    for (const i in this) { 
        if (callback(this[i])) { 
            sum += this[i]; 
        } 
    } 
    return sum; 
};
const arr = [1, 2, 3, 4, 5, 6]; 
function callback(ele) { 
    if (ele % 2 == 0) { 
        return true; 
    } 

    return false; 
} 
const sum = arr.myReduce(callback, 0); 
console.log(sum);//Output : 12

Conclusion-

This is how Polyfills create . It are essential for maintaining cross-browser compatibility when using modern JavaScript features. They help ensure that your code works seamlessly across both modern and older environments, providing a consistent user experience

Read more blogs


I’m truly thankful for your time and effort in reading this.