Open In App

Implement polyfill for Array.prototype.reduce() method in JavaScript

In this article, we will learn how to implement a polyfill for an Array.prototype.reduce() method in JavaScript. 

A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or the new version of the browser does not have that feature. 



We will discuss the reduce() method supported by arrays in JavaScript, and implement our own version of it as well. The reduce() method calls a callback function, called a reducer function, on every element of the array one-by-one, and returns a single value as an output. 

Example: 






<script>
    const arr = [1, 2, 3, 4];
  
    // Find sum of array elements
    // using reduce method
    const sum = arr.reduce((total, num) => total + num);
  
    console.log(sum);
</script>

Output:

10

Array.prototype.reduce(): Let us create our own simple polyfill for the reduce() method.

Example:




<script>
    Array.prototype.myReduce = function (callback, initialValue) {
  
        // Variable that accumulates the result
        // after performing operation one-by-one
        // on the array elements
        let accumulator = initialValue;
  
        for (let i = 0; i < this.length; i++) {
              
            // If the initialValue exists, we call
            // the callback function on the existing
            // element and store in accumulator
            if (accumulator) {
                accumulator = callback.call(undefined, 
                    accumulator, this[i], i, this);
                  
                // If initialValue does not exist, 
                // we assign accumulator to the
                // current element of the array
            }
            else {
                accumulator = this[i];
            }
        }
  
        // We return the overall accumulated response
        return accumulator;
    }
  
    // Code to calculate sum of array elements
    // using our own reduce method
    const arr = [1, 2, 3, 4];
    console.log(arr.myReduce((total, elem) => total + elem));
  
    // Code to calculate multiplication of all array elements
    console.log(arr.myReduce((prod, elem) => prod * elem));
</script>

Output: 

10
24

Article Tags :