What is Polyfill?  Make it for ForEach

What is Polyfill? Make it for ForEach

A Polyfill is a code in JS which is used to provide modern functionality on old browser which is not supported in old versions. Basically mimic the modern functionality with traditional code.
For Example: forEach will not work in the older version of edge browser.

Lets do the polyfill of forEach:

Array.prototype.customForEach = function(callback, thisContext){
    // Check if the provided callback is a function
    if(typeof callback !== 'function') {
        throw new Error("Please pass a valid callback function!");
    } else {
        // Get the length of the array
        let arrLength = this.length;

        // Iterate over each element of the array
        for(let i = 0; i < arrLength; i++) {
            // Check if the current element hasOwnProperty method (optional check)
            if(this[i].hasOwnProperty) {
                // Call the provided callback function with the specified context and arguments
                callback.call(thisContext, this[i], i, this);
            }
        }
    }
}

Explaination: Let's break down the above polyfill:

  1. Array.prototype.customForEach: This adds a new method called customForEach to the prototype of the Array object.

  2. The method takes two parameters:

    • callback: The function to execute for each element in the array.

    • thisContext: The context (this value) to use when calling the callback function.

  3. It checks if the provided callback is a function. If not, it throws an error.

  4. It retrieves the length of the array using this.length.

  5. It iterates over each element of the array using a for loop.

  6. Inside the loop, it checks if the current element has a hasOwnProperty method (this check is optional and may not be necessary).

  7. It calls the provided callback function for each element, using call to set the specified context (thisContext). The callback function is called with three arguments:

    • this[i]: The current array element.

    • i: The index of the current array element.

    • this: The array itself.

This polyfill essentially provides a custom implementation of the forEach method for arrays that may be used in environments where the native forEach method is not available or needs to be extended.