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


The polyfill is a concept to extend the browser's features using user-defined methods. If the user’s browser is not updated, it can happen that browser doesn’t support the newer features of any programming language, such as JavaScript.

As a developer, we require to check whether the feature is supported by the browser, and if not, we need to invoke a user-defined method.

In this tutorial, we will discuss implementing the polyfill for the array.reduce() method. If any browser doesn’t support the array.reduce() method, we will invoke the userdefined reduce() method.

Before we start with the tutorial, Let’s understand what reduce() method does. The reduce() method reduces the array into a single element. For example, We can use the array.reduce() method to find the sum of all elements in the array as we reduce all array elements into the single sum variable. Also, we can use the reduce() method to concat all strings of the array into a single string.

Syntax

Users can follow the syntax below to implement the polyfill for the array.reduce() method.

Array.prototype.reduce = function (callbackFunc, initial) {
   
   // implement logic for reduce() method
} 

In the above syntax, we have added the reduce() method to the prototype object of the Array object. We need to implement the logic of reduce() method inside the function.

Example (Using the built-in reduce() method)

In the example below, we created the array of numbers and used the reduce() method to get a sum of all array elements. Users can observe how we have reduced the array into a single element.

<html>
<body>
   <h2>Using the <i> reduce() method without polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      function callback(sum, value) {
         return sum + value;
      }
      let array = [30, 50, 6, 7, 8, 9, 50, 3, 2, 3, 43, 5, 4, 3, 23, 32, 456];
      let sum = array.reduce(callback, 0);
      content.innerHTML += "The array values are " + array + "<br>";
      content.innerHTML += "The sum of all array elements using the array.reduce() method is " + sum + "<br>";
   </script>
</body>
</html>

Implementing the polyfill for reduce() method

Users should follow the below steps to implement the logic of the array.reduce() method.

Step 1 – Create a singleElement variable and initialize it with the initial value passed as an argument. Also, the initial is an optional parameter, so it can be undefined if users haven’t passed the initial value as an argument of the reduce() method.

Step 2 – Use the for loop to iterate through the array.

Step 3 – If the value of singleElement is undefined, initialize it with the first element of the array.

Step 4 – Use the call() method to execute the callback function for every array element and replace the value of the singleElement variable with returned value from the callback function.

Step 5 – Once the iteration of for loop completes, return the singleElement variable’s value.

Example

In the example below, we are doing the sum of the array elements using the reduce() method as in the above example, but here we are using the user-defined reduce() method.

We have followed the above steps to implement the user-defined reduce() method, and users can observe that it gives the same output as previous example.

<html>
<body>
   <h2>Using the <i> reduce() method with polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      function callback(sum, value) {
         return sum + value;
      }
      let array = [30, 50, 6, 7, 8, 9, 50, 3, 2, 3, 43, 5, 4, 3, 23, 32, 456];
      Array.prototype.reduce = function (callbackFunc, initial) {
         
         // initial is an optional parameter.
         
         // if initial passed as an argument, initialize the singleElement with the initial value.
         
         // Otherwise, initialize the singleElement with the first value of the array. 
         let singleElement = initial;
         for (let k = 0; k < this.length; k++) {
            if (singleElement) {
               singleElement = callbackFunc.call(null,
               singleElement, this[k], k, this);
            }
            else {
               singleElement = this[k];
            }
         }
         
         // return the single element.
         return singleElement;
      }
      let sum = array.reduce(callback)
      content.innerHTML += "The array values are " + array + "<br>";
      content.innerHTML += "The sum of all array elements using the array.reduce() method is " + sum + "<br>";
   </script>
</body>
</html>

Example

We have optimized the polyfilled reduce() method in the example below. We have used the forEach() method inside the reduce() method to improve iteration performance. Also, we have used the ternary operator to initialize the start variable.

Furthermore, we have defined the array of strings and converted all array elements into a single string using the array.reduce() method.

<html>
<body>
   <h2>Using the <i> reduce() method with polyfill </i> in JavaScript</h2>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      Array.prototype.reduce = function (callbackFunc, start) {
         let array = this;
         array.forEach(value => {
            start = start !== undefined ? callbackFunc(start, value) : value
         })
         return start;
      }
      function callback(finalStr, str) {
         return finalStr + str;
      }
      let strings = [" Hi ", " Users ", "!", " Welcomes ", " to ", " the ", " tutorialspoint's ", " JavaScript ", " blog! "];
      let finalStr = strings.reduce(callback, "")
      content.innerHTML += "The array values: " + strings + "<br>";
      content.innerHTML += "The final string after merging all array values using the array.reduce() method: " + finalStr + "<br>";
   </script>
</body>
</html>

We learned to implement the polyfill for the array.reduce() method. We have seen two different approaches to implementing the user-defined reduce() method. Users should use the second approach as it is shorter, more readable, and cleaner.

Updated on: 28-Feb-2023

843 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements