Skip to main content

Command Palette

Search for a command to run...

Polyfill for forEach()

Published
2 min read
Polyfill for forEach()

What is Polyfill?

Polyfill is a piece of code (or plugin) that offers the functionality that you, the developer, would expect the browser to deliver natively. It’s a service that takes a request for a set of browser features and only delivers the polyfills the requesting browser requires.

forEach()

The forEach() method in JavaScript is used to iterate across an array; developers will find this function quite useful. For each array element, the forEach() method calls a given function once. A forEach polyfill is a piece of JavaScript code that implements the native Array.prototype.forEach method for older web browsers or environments that do not natively support it.

If you are interviewing as a fresher, they will expect you to implement a custom forEach.

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

Recommended for SDE-2/SDE-3 interview preparation

Array.prototype.useForEach = function(callback, thisCtx) {
    if( typeof callback !== 'function' ) {
        throw new TypeError(callback + ' is not a function');
    }

    let length = this.length;
    let i =0;

    while(i <length) {
        if(this.hasOwnProperty(i)) {
            callback.call(thisCtx, this[i], i, this);
        }
        i++;
    }
}
let arr = [1, 2, 3];
arr.useForEach(function(item) {
    console.log('item: ' + item);
});

//output. 
//item: 1
//item: 2
//item: 3