JavaScript array has an inbuilt method forEach
which takes a callback function as input and executes this callback function with each element of the array.
Example
const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // "a" // "b" // "c"
The forEach method takes 3 parameters as input,
- Current array element.
- Element’s index.
- Context (Array itself).
Using the same as a reference we will be creating the polyfill of array forEach method.
Array.forEach polyfill
It is extremely common question in JavaScript interviews where it is asked to implement polyfill for the forEach()
method.
A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers.
As seen above, Array.forEach have these functionalities
forEach()
function should take an callback function as an argument.- Current element, its index, and the context should be passed as an argument to the callback function.
Array.prototype.forEach = function (callback, context) { for (let i = 0; i < this.length; i++) { // This is primarily to check if the item // exists in the array, if (this.indexOf(this[i]) > -1) { callback.call(context, this[i], i, this); } } }