Polyfills :- Making JavaScript workable in every browser

Sanket SinghSanket Singh
8 min read

when you sometimes open a latest website on old versions web browsers do you ever encounter a website crash. or some components of website not loading properly. This is because, there are some features or you can say functions/methods in JavaScript which are put in code of webpage but not supported by some browsers. So, to overcome this issue and make webpage accessible at every version of browsers all developers write these unavailable methods by themself and loads into the web browser along with the website. These customs code written by developers which are not supported by web browsers are know as “ PolyFills ”.

So, in this blog we are going to study about the PolyFills and see how can we write these. After, that we will see some common polyfills that every developer should know. So, without wasting time let’s get started.


What is a Polyfill ?

A Polyfill is basically a small piece of code that ( generally JavaScript on web ) that is used to provide modern functionality to older web browsers that do not natively support it.

In other words, Polyfills are mimic of built-in functions / JavaScript methods which are missing or not supported by the certain web browsers. For example, the array instance method Array.prototype.flat was introduced in (ES2019) and i snot supported by the Internet Explorer. So, the polyfill add that method to Internet explorer to work properly.


The Need of Polyfills

  1. New Features :- Polyfills enable developers to use cutting edge features of a programming language or a web platform in older version of web browser that don’ t support them.

  2. Browser Compatibility :- The latest features of a programming language or web platform may not be supported by all browsers and environments, which can cause compatibility problems for developers. Polyfills ensure that the code functions consistently on various browsers and gadgets.


How to write Polyfiils in JavaScript ?

Now, let’s see how can we write the polyfills in JavaScript. The following are the steps included in order to write the your own polyfills in JavaScript :-

Step 1 :- Identify the missing method

  • First of all find the missing Function/method from the web browser. The missing function/method can be found by using the feature detection methods like typeof, in or window.

Step 2 :- Define the missing method

  • Once you found the missing method, define it using the protoype ( for instance method ) and globally ( for static method ).

    prototype :- prototype is basically an object that stores methods and properties shared among all the instances of a particular constructor function like Array, Object or Function

  • Ensure that our polyfill follow all the rules of the ECMAScript specifications for proper and consistent Functioning.

Step 3 :- Testing the Polyfill

  • Once you created the polyfill test it across various web browsers and at different versions of the web browser.

This the steps we need to write the polyfills in Javascript. Now, let’s see some common JavaScript polyfills.


Common Polyfills that every Developer should Know !

Here, i am going to define some pollyfills of the Array object in javascript. So, let’s saw each of them one by one :-

Array.prototype.filter

The filter() method of the Array, filter out the elements from the original array based upon the condition provided by the user and return a new array.

Signature :-

Input :- Takes a callback Function

Output :- Return a new array

Task :- filter out elements based upon the condition in callback function

Code :-

if(!Array.prototype.Myfilter){ // checking if function already exists or not
    Array.prototype.Myfilter = function(callbackFn) { // Creating polyfill
        const result = []
        for(let i = 0;i < this.length; i++){
            if(callbackFn(this[i], i)){
                result.mypush(this[i]);
            }
        }
        return result;
    }
}

Testing the Polyfill :-

const arr = [1,0,-1,3,4,2,6]
const Updated_array = arr.Myfilter((item) => {
    return item > 2
})
console.log(Updated_array) // Output :- [ 3, 4, 6 ]

Array.prototype.map

The map() method of the array iterates over each element of the original array and do action on each element based upon the user function and returns the new array.

Signature :-

Input :- Takes a user Function

Output :- Return a new array

Task :- iterates over each element of the original array and do action on each element based upon the user function

Code :-

if(!Array.prototype.Mymap){
    Array.prototype.Mymap = function (userFn) {
        const result = []
        for(let i = 0;i < this.length; i++){
            result.mypush(userFn(this[i], i))
        }
        return result;
    }
}

Testing the Polyfill :-

const arr = [1,2,3,4]
const Updated_array = arr.Mymap(element => element * 2) // Multipying each element by 2
console.log(Updated_array); // Output :- [ 2, 4, 6, 8 ]

Array.prototype.includes

The includes() method of the array iterate over the entire original array and find whether the includes a certain value or not. Return true or false as output.

Signature :-

Input :- Takes an element which is to be searched and an Starting Index which can be -ve

Output :- Return a boolean value

Task :- iterates over each element of the original array and find the certain value

Code :-

if(!Array.prototype.MyIncludes){
    Array.prototype.MyIncludes = function (serachElement, startIndex = 0) {
        startIndex = startIndex >= 0 ? startIndex : Math.max(0, this.length - Math.abs(startIndex))
        for(let i = startIndex; i < this.length; i++){
            if(this[i] == serachElement){
                return true;
            }
        }
        return false;
    }
}

Testing the Polyfill :-

const array1 = [1, 2, 3];
console.log(array1.MyIncludes(2));
// Expected output: true
const pets = ["cat", "dog", "bat"];

console.log(pets.MyIncludes("cat"));
// Expected output: true
console.log(pets.MyIncludes("at"));

Array.prototype.join

The join() method of the array returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string.

Signature :-

Input :- Takes an element by which elements be separated

Output :- Return a new string

Task :- iterates over each element of the original array and merge it into string separated by separator

Code :-

if(!Array.prototype.MyJoin){
    Array.prototype.MyJoin = function (seprator) {
        if(seprator == undefined) seprator = ",";
        let result = "";
        for(let i = 0;i < this.length; i++){
            result += this[i];
            if(i != this.length - 1){
                result += seprator;
            }
        }
        return result;
    }
}

Testing the Polyfill :-

const elements = ["Fire", "Air", "Water"];

console.log(elements.MyJoin());
// Expected output: "Fire,Air,Water"
console.log(elements.MyJoin(""));
// Expected output: "FireAirWater"
console.log(elements.MyJoin("-"));

Array.prototype.concat

The concat() method of the array is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Signature :-

Input :- Takes number of arrays that to be merge

Output :- Returns a new merged array

Task :- iterates over each array and merge them

Code :-

if(!Array.prototype.MyConcat){
    Array.prototype.MyConcat = function () {
        const result = [...this]

        for(let i = 0;i <arguments.length; i++){
            for(let j = 0;j <arguments[i].length; j++){
                result.mypush(arguments[i][j])
            }
        }
        return result
    }
}

Testing the Pollyfill :-

const array1 = ["a", "b", "c"];
const array2 = ["d", "e", "f"];
const array3 = array1.MyConcat(array2);

console.log(array3); // Output :- ["a", "b", "c", "d", "e", "f"]

Array.prototype.every

The every() method of the array iterates over the whole array and checks if each element passing the test implemented by the user function and return true if pass else, false.

Signature :-

Input :- Takes a user Function

Output :- Returns a boolean value

Task :- iterates over each element of the array and checks the condition

Code :-

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

Testing the Polyfill :-

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.Myevery(isBelowThreshold));
// output: true

Array.prototype.slice

The slice() method() of the array is used to get the portion of the array from the original array without modifying the array selected from startIndex to endIndex. It returns a new array conatinig all the selceted element.

The start and end index may be NEGATIVE so be careful!

Signature :-

Input :- Takes a starting Index and and ending Index (ending not included)

Output :- Returns a new array

Task :- Take out the specified portion from the original array

Code :-

if(!Array.prototype.MySlice){
    Array.prototype.MySlice = function (startIndex = 0, endIndex = this.length) {
        startIndex = startIndex >= 0 ? startIndex : Math.max(0, this.length - Math.abs(startIndex))
        endIndex = endIndex < 0 ? Math.max(0, this.length - Math.abs(endIndex)) : Math.min(this.length, endIndex)

        const result = [];
        for(let i = startIndex;i < endIndex; i++){
            result.push(this[i])
        }
        return result;
    }
}

Testing the Polyfill:-

const animals = ["ant", "bison", "camel", "duck", "elephant"];

console.log(animals.MySlice(2));
// output: ["camel", "duck", "elephant"]
console.log(animals.MySlice(2, 4));
// output: ["camel", "duck"]
console.log(animals.MySlice(1, 5));
// output: ["bison", "camel", "duck", "elephant"]
console.log(animals.MySlice(-2));
// Expected output: Array ["duck", "elephant"]
console.log(animals.MySlice(2, -1));
// output: ["camel", "duck"]
console.log(animals.MySlice());
// output: ["ant", "bison", "camel", "duck", "elephant"]

So, these are the some common polyfills of the aray that every programmer should know ! Take a reference from this and try to write polyfills for the remaining methods.


Conclusion

Polyfills are small code piece that enable modern web functionalities to work on older browsers lacking native support, ensuring consistent behavior across diverse browsers. In this article we studied deeply about the polyfills and saw some common polyfills of the Array. I hope this article helps you to understand the polyfills. Thanks for reading my article. Please like my article and feel free for any suggestion in comment section. Bye all !

11
Subscribe to my newsletter

Read articles from Sanket Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sanket Singh
Sanket Singh