DEV Community

Imran shaikh
Imran shaikh

Posted on • Updated on

Javascript Array Polyfills, How to create polyfills in JS

In my interview journey , I have seen 80% of the company is asking this hot topic called polyfills. So before applying to the job interview you should have thorough understanding of polyfills.
But you might be thinking why companies are asking polyfills in interview process.
Because it covers lot of in-depth understanding of JS concepts like prototype, this, understanding to method and functions that is why interviewer is keen to know about polyfills.

What is polyfill.

A polyfill is code that implements a feature on web browsers that do not support the feature.

There are so many polyfills available but i will cover only famous array polyfill code below

Image description

Array.prototype.myMap = function(callback){
    const arr = [];
    for(let i=0; i<this.length; i++){
        arr.push(callback(this[i],i,this));
    }
    return arr;
}

Array.prototype.myFilter = function(callback){
    const arr = [];
    for(let i=0; i<this.length; i++){
        if(callback(this[i],i,this)){
            arr.push(this[i]);
        }
    }
    return arr;
}

Array.prototype.myForEach = function(callback){
    for(let i=0; i<this.length; i++){
        callback(this[i],i,this);
    }
}
Array.prototype.myFind = function(callback){
    for(let i=0; i<this.length; i++){
        const res = callback(this[i],i,this);
        if(res){
            return this[i];
        }
    }
    return undefined;
}

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

// --------------------reduce function polyfills--------------------
Array.prototype.myReduce=function(){
    const callback = arguments[0];
    let currentVal = arguments[1];
    for(let i=0; i<this.length; i++){
      let result = callback(currentVal, this[i], i ,this);
      currentVal = result;
    }
    return currentVal;
}

var logicAlbums = [
    'Bobby Tarantino',
    'The Incredible True Story',
    'Supermarket',
    'Under Pressure',
  ]
var withReduce = logicAlbums.myReduc(function(a, b) {
    return a + ' , ' + b
}, 'Young Sinatra')
Enter fullscreen mode Exit fullscreen mode

Thank you for reading.

If you want to see more polyfills and interview questions please go my github account
https://github.com/imran-mind/javascript-notes/tree/master/JS-Polyfills

Top comments (0)