Essential Polyfills Every Developer Needs to Know

Essential Polyfills Every Developer Needs to Know

As I was going through old articles and blogs, I read many things about JavaScript and how it is becoming more and more advanced for different browsers. With each new update, JavaScript introduces powerful features that enhance performance, security, and developer experience.However, many browsers are still very slow in adopting new standards. For example, Internet Explorer and older versions of Microsoft Edge (pre-Chromium) struggle with performance and lack support for many modern JavaScript features.

In this blog, I will walk you through how to create your own polyfills for different array methods like push, pop, filter, map, forEach, reduce, includes, and shift. These polyfills allow’s us to use modern functonality of array method’s in older browser.

What is polyfills?

A polyfill is a piece of code that provides functionality to a user's browser if a certain website's functionality is not supported. It enables modern features for the user even on older browsers.polyfills are used to address issues where browsers implement the same features in different ways. The polyfill uses non-standard features in a certain browser to give JavaScript a standards-compliant way to access the feature.

Before writing polyfills, first, understand the correct syntax for defining them. The syntax follows this structure:

Array.prototype.methodName = function() {
    // Method implementation
};

1.Polyfill Array.prototype.push()

The push() method is used to add elements to the end of an array and return the upadted array.

if (!Array.prototype.mypush) {
  Array.prototype.mypush = function (...element) {  // 'element' is an array of arguments passed to mypush

    // this is the Loop through each argument passed to the function
    for (let i = 0; i < element.length; i++) {
      // Add each element to the end of the array
      this[this.length] = element[i];
    }

    // this  Return the updated array
    return this;
  };
}
const arr = ["Mango", "icecrem", "mobile"];
const output = arr.mypush("push this bro", "ok bro it's been pushed");
console.log(output);  // Output: ["Mango", "icecrem", "mobile", "push this bro", "ok bro it's been pushed"]

2.Polyfill Array.prototype.pop()

The pop() method removes the last element from an array and returns that element. It also updates the array's length by reducing it by 1.

if (!Array.prototype.mypop) {
  Array.prototype.mypop = function () {
    if (this.length === 0) return undefined; // this statement returns undefined if there is an empty array
      this.length = this.length - 1;
        return this.length;
    }
  };

const arr = ["mango", "grapes", "apple", "banana"];
const result = arr.mypop();
console.log(result); //length of the array
console.log(arr); // the final aray by removing the last element

3.Polyfill Array.prototype.filter()

The filter() method is used to filter elements from an array based on a given condition. It creates a new array with only the elements that satisfy the condition.

//polyfill for the filter method
if(!Array.prototype.myfilter){
    Array.prototype.myfilter=function(userfn){
        const newarr=[];
        for(let i=0;i<this.length;i++){
           if(userfn(this[i])){
            newarr.push(this[i]);
           }
        }
        return newarr;
    }
}
const arr=[10,17,20,3,6,2];
const result=arr.myfilter((e)=> e % 2==0 ? true:false); //condtion for the filter method
console.log(result);  // [ 10, 20, 6, 2 ]

4.Polyfill Array.prototype.reduce()

The reduce() method in JavaScript reduces an array to a single value by applying a function that processes each element and accumulates the result. It is commonly used for summation, multiplication, finding maximum/minimum.

if (!Array.prototype.myreduce) {
  Array.prototype.myreduce = function (userfn) {
    let result =this[0];
    for (let i = 1; i < this.length; i++) {
      result=userfn(result,this[i])
    }
    return result

  };
}

const arr = [10, 20, 30, 40];
const output = arr.myreduce((acc, cur) => acc + cur);
console.log(output); //100

5.Polyfill Array.prototype.map()

The map() method creates a new array by applying a function to each element of an existing array. It does not change the original array.

//polyfill for map method
if(!Array.prototype.mymap){
    Array.prototype.mymap=function(userfn){
        const newarr=[];
        for(let i=0;i<this.length;i++){
            newarr.push(userfn(this[i],i));

        }
           return newarr;
    }
}
const test=[10,20,30];
const result=test.mymap((e) => e*3);
console.log(result); //[ 30, 60, 90 ]

6. Polyfill Array.prototype.foeach()

The forEach() method is used to execute a function on each element of an array

//pollyfills of the for each
if(!Array.prototype.myforeach){
  Array.prototype.myforeach=function(userfucntion){
          const orginalarry=this;
          for(let i=0;i<this.length;i++){
            userfucntion(orginalarry[i],i);
          }
  }
}
const testarray=[10,20,30,40,50];
testarray.myforeach(function(value,index){
  console.log(`item at index ${index} : ${value}`); 
});
// item at index 0 : 10
// item at index 1 : 20
// item at index 2 : 30
// item at index 3 : 40
// item at index 4 : 50

7.polyfill Array.prototype.includes()

The includes() method checks if a given value exists in an array and returns true or false.

if(!Array.prototype.myincludes){
    Array.prototype.myincludes=function(userfn){
       for(let i=0;i<this.length;i++){
       if(this[i]===userfn){
        return true;
       }
    }
}
}

const arr=["Mango","Apple","Mobile","pen"]
const result=arr.includes("laptop");
console.log(`Result ${result}`); //false
const result2 = arr.includes("Apple");
console.log(`Result2 ${result2}`); //true

8.polyfill Array.prototype.shift()

The shift() method removes the first element from an array and returns it.

if(!Array.prototype.myshift){
    Array.prototype.myshift=function(){
        if(this.length === 0)return undefined;
        const firstelement=this[0];
        for(let i=0;i<this.length-1;i++){  
              this[i]=this[i+1];
        }
        this.length=this.length-1;
         return firstelement;
    }

}

const arr=["mango","mobile","apple","cartoon"];
const output=arr.myshift();
console.log(arr); //the final arr [ 'mobile', 'apple', 'cartoon' ]