Javascript Array Polyfills, How to create polyfills in JS.

Javascript Array Polyfills, How to create polyfills in JS.

In my interview journey, I have seen 80% of the company asking about this hot topic called polyfills. So before applying to a job interview, you should have a thorough understanding of polyfills.

But you might be thinking why companies are asking for polyfills in the interview process.

Because it covers a lot of in-depth understanding of JS concepts like prototypes, this, understanding of methods and functions that is why interviewer is keen to know about polyfills.

What is polyfill?

A polyfill is a 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 codes below

Polyfill of forEach() method.

Array.prototype.myForEach = function(callback){ for(let i=0; i<this.length; i++){ callback(this[i],i,this) } }

Polyfill of map() method.

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

Polyfill of filter() method.

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; }

Polyfill of find() method.

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; }

Polyfill of reduce() method

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’)

Polyfill of every() method

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

Polyfill of some() method.

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

Thank you for reading, If you like please hit the Like button, Please don't forget to share.