Poly fills: Fallback for Old Browsers!"

MOHIT WAGISHMOHIT WAGISH
4 min read

In JavaScript, we have many built-in methods for objects, arrays, strings, and numbers. But where do these methods come from? Who gives them their "superpowers"?

The answer is the browser's JavaScript engine. However, browsers don’t randomly decide how these methods work. There is a set of official guidelines created by TC39 (the team behind JavaScript standards). These guidelines define how methods should behave, but each browser's developers are responsible for implementing them in a way that optimizes performance.

For example ,the toSorted() function was introduced in ECMAScript 2023

and we can see which browser supports this array function-

The Problem

Not all browsers update at the same time. Some, like Internet Explorer, take a long time to adopt new JavaScript features. Also, many users don’t update their browsers regularly.

So, if you use the latest JavaScript features in your program, some users' browsers might not recognize them, causing your website to crash.

The Wrong Solution

You might think:
"I'll just tell users to update their browser before using my website!"

But that sounds rude and could drive customers away. If someone is using Internet Explorer, you’ve already lost them.

The Right Solution: Polyfills!

This is where Doctor Polyfill comes to the rescue! 🦸‍♂️

A polyfill is a fallback solution that checks if a function is missing in the browser. If it’s not available, we write our own version of that function and inject it into the environment.

💡 Polyfills ensure that your code works everywhere, even on older browsers!

Rules to write Poly fills-

  1. Real signature ko samjho -

    a. Kya kuch return kr raha hai

    b. Input kya le raha hai,

    c. naya array/ya phir jiske liye ap polly fill likh rahe ho return kar raha, ya same array or object ko change kr raha hai.

Syntax to write pollyfills-

if(!array.prototype.mymap)//iska mtlb array me mymap agar nahi hai toh 
{
array.prototype.mymap = function(callback function)// yeh function ko inject kro
{
...........
}
}

So, lets see all the common array methods in form of pollyfills,

1. Array.prototype.myat

//takes integer as an input ,that can be negative (bs range me hona chahiye)
//ar index pr jo value hai return krega

if(!Array.prototype.myat){
    Array.prototype.myat=function(index){
        if(index>0 && index<this.length){
            return this[index];
        }
        else if(index<0){    // handeling negative index
            return this[(this.length)+index]; // kyuki index already -ve hai
        }
        else{
            return undefined; // handing error index out of range wala

        }
    }
}

let a = [1,5,8,6]

console.log(a.myat(2))
console.log(a.myat(-1)) //length=4,index=-1 so at index=3 value is 6
console.log(a.myat(8))

2.Array.prototype.myconcat

// as it do not disturb original array and return a new array
//takes an array as input

if(!Array.prototype.myconcat){
    Array.prototype.myconcat=function(arr2){
        let new_arr=[]
        if(arr2.length==0){
            new_arr=[...this]; // just for fun
            return new_arr;
        }
        else{
            new_arr=[...this,...arr2] //used spread operator we could have used for loop for 2nd array

        }
        return new_arr;
    }
}

let ar1=[1,8,6]
let ar2 =[8,9,9]
let ar3=ar1.myconcat(ar2)

3 Array.myevery

//expects an boolean callback function as input
//gives true if all value is true and false if one case is false
if(!Array.prototype.myevery){
    Array.prototype.myevery= function(callbackfunc){
        for(let i=0;i<this.length;i++){
            if (callbackfunc(this[i])==false){
                return false;
            }
        }
        return true;
    }
}

a1=[4,8,2,9]
let ans = a1.myevery((e)=>{if(e%2==0){return true}else{return false}})
console.log(ans);

4 Array.myfilter

//expects a callback ffunction
// return the value which pass the conddition

if(!Array.prototype.myfilter){

        Array.prototype.myfilter= function(callbackfunc){
            let myarr=[];
            for(let i=0;i<this.length;i++){
                if (callbackfunc(this[i])===true){
                    myarr.push(this[i])
                }
            }
            return myarr;

        }
    }


let a= [2,5,8,9]
console.log(a.myfilter(e=>e%2===0));

5 Myfind

// expect callback function
//output - as first element found which satisfy the condition
if(!Array.prototype.myfind){
    Array.prototype.myfind=function(callback){
        for(let i=0;i<this.length;i++){
            if((callback(this[i]))===true){
                return this[i];
            }

        }
        return undefined;
    }
}

let a = [5,9,2,1,8];

let ans = a.myfind(e=>e>5)
console.log(ans);

6 Flatten

// flatten expect an nested array and depth of recursion to take out element
// expected output is return of new array with depth of recursion

if (!Array.prototype.myFlat) {
    Array.prototype.myFlat = function(depth = 1) { 
        const result = [];

        function flatten(arr, currentDepth) {
            for (let item of arr) {
                if (Array.isArray(item) && currentDepth < depth) {
                    flatten(item, currentDepth + 1); // recursion with increase in depth 
                } else {
                    result.push(item);
                }
            }
        }

        flatten(this, 0);
        return result;
    };
}


let arr = [1, [2, 3], [4, [5, 6, [7, 8]]]];

console.log(arr.myFlat());      // Output: [1, 2, 3, 4, [5, 6, [7, 8]]]  (default depth = 1)
console.log(arr.myFlat(2));     // Output: [1, 2, 3, 4, 5, 6, [7, 8]]    (depth = 2)
console.log(arr.myFlat(Infinity)); // Output: [1, 2, 3, 4, 5, 6, 7, 8]  (fully flattened)

7 For each

// For each loop accept a call back function
// this function do not return new array, 
//it just apply the call back function on each element of array

if(!Array.prototype.myForeach){
    Array.prototype.myForeach=function(callbackFunc){
        for(let i=0;i<this.length;i++){
            callbackFunc(this[i])
        }
    }
}

let a = [45,48,4,11]
let an = a.myForeach(a=>console.log(a));

This is all polyfills i did as on Thrusday, my goal is to do all the array poly fills in coming days.

Thankyou for reading.

6
Subscribe to my newsletter

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

Written by

MOHIT WAGISH
MOHIT WAGISH