Creating a Polyfill for the Reduce Method

The reduce method in JavaScript is an essential array method that helps in accumulating a single result from an array by applying a function to each element. It’s incredibly useful for tasks like summing up numbers, concatenating strings, or merging objects.

In this interview article, we’ll explore how to create a polyfill for the reduce method, ensuring it works seamlessly across all JavaScript environments.

Understanding the reduce Method

The reduce method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

  1. Accumulator: The accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
  2. Current Value: The current element being processed in the array.
  3. Source Array: The array reduce was called upon.

Here’s a simple example of the reduce method:

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, current) => acc + current, 0);
console.log(sum); // Output: 10

Step-by-Step Implementation

Define the myReduce method, which accepts a callback function and an optional initial value.

  Array.prototype.reduce = function(callback, initialValue) {

Iterate over the array, applying the callback function to each element accumulating the result and finally returning the accumulated value.

Array.prototype.myReduce = function(callback, initialValue) {
  if (this === null || this === undefined) {
    throw new TypeError('reduce called on null or undefined');
  }
  
  let value = initialValue;
  for (let index=0; index < this.length; index++) {
    if (index in this) {
      value = callback(value, this[index], index, this);
    }
  }

  return value;
};
  
const numbers = [1, 2, 3, 4];
const sum = numbers.myReduce((acc, current) => acc + current, 0);
console.log(sum); // Output: 10

We will assign the accumulator to another variable(value), and we will be iterating over the array, and we will call the callback function and whatever this callback function returns, we will reassign that to the variable(value), and at the end we will be returning the value.

This is how we can create a polyfill for the the reduce array method.