DEV Community

Cover image for .forEach() Polyfill
Swapnadeep Mohapatra
Swapnadeep Mohapatra

Posted on

.forEach() Polyfill

What is a polyfill?

Polyfill is code that implements a feature on web browsers that is expected to be provided by the browser natively but is not available. The developer uses one's logic to implement the solution.

What is .forEach()

It is an array function that is used to iterate over an array. This function comes in handy when we don't want to implement the for loop from scratch, hence saving a lot of time as well as some lines of code.

The function is applied in an array and takes in another function as a parameter (known as callback function). In the callback function's parameters the current element of the array, index , and the complete array are passed.

Writing the Polyfill

We will be iterating over an array of some listed companies in NSE.

var nseStocks = [
  'PIDILITIND',
  'ASIANPAINT',
  'ZOMATO',
  'RELIANCE',
  'INFY',
]
Enter fullscreen mode Exit fullscreen mode

Firstly let's try running the native .forEach()

nseStocks.forEach(function (stock) {
  console.log(stock);
});

// PIDILITIND
// ASIANPAINT
// ZOMATO
// RELIANCE
// INFY
Enter fullscreen mode Exit fullscreen mode

So, we will be adding the forEach function to the prototype of Array.

Array.prototype.myForEach = function (callback) {
  for (var i = 0; i < this.length; i++) {
    callback(this[i], i, this)
  }
}
Enter fullscreen mode Exit fullscreen mode

Now let's try running our polyfill.

nseStocks.myForEach(function (stock) {
  console.log(stock);
});

// PIDILITIND
// ASIANPAINT
// ZOMATO
// RELIANCE
// INFY
Enter fullscreen mode Exit fullscreen mode

Connect with me

For more awesome JS or WebDev related blogs check out my profile

LinkedIn My Portfolio Twitter Instagram

Top comments (0)