DEV Community

Cover image for Polyfills for .forEach(), .map(), .filter(), .reduce() in JavaScript
umerjaved178
umerjaved178

Posted on

Polyfills for .forEach(), .map(), .filter(), .reduce() in JavaScript

A piece of code that provide native support to the older browsers who does not have the support of modern functionalities of javascript is known as polyfill.

forEach

The forEach() executes the callback function on each element of array.

const names = ["ali", "hamza", "jack"];
function consoleFunc(x) {
   console.log(x);
}
names.forEach(consoleFunc);

// console
// ali hamza jack
Enter fullscreen mode Exit fullscreen mode

Let's make its polyfill

Array.prototype.ourForEach = function (callBack) {
  for (let i = 0; i < this.length; i++) {
    callBack(this[i]);
  }
};
names.ourForEach(consoleFunc);

// console
// ali hamza jack
Enter fullscreen mode Exit fullscreen mode

Array.prototype let use run our function on every array
this corresponds to the array

map

.map() is very much similar to .forEach() method, except, instead of returning items out of the array, it return the array itself

const users = [1, 2, 3, 4, 5];
function double(x) {
  return x + x;
}
const newUsers = users.map(double);
// console
// [1, 4, 9, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Let's make its polyfill

const users = [1, 2, 3, 4, 5];
Array.prototype.ourMap = function (callBack) {
  const newArray = [];
  for (let i = 0; i < this.length; i++) {
    newArray.push(callBack(this[i]));
  }
  return newArray;
};
console.log(users.ourMap(double));

// console
// [1, 4, 9, 8, 10]
Enter fullscreen mode Exit fullscreen mode

filter

.filter() decide what kind of items do we want in the resulting array.

const logicAlbums = [
  {
    name: "Bobby Tarantino",
    rating: 5,
  },
  { name: "The Incredible True Story", rating: 4.5 },
  {
    name: "Supermarket",
    rating: 4.9,
  },
  {
    name: "Neon",
    rating: 4.2,
  },
  { name: "Under Pressure", rating: 5 },
];

function greaterThan(x) {
  return x.rating > 4.5;
}

const filtered = logicAlbums.filter(greaterThan);
console.log(filtered)

// console
// [ 
// {name: "Bobby Tarantino", rating: 5},
// {name: "Supermarket", rating: 4.9},
// {name: "Under Pressure", rating: 5}
// ]
Enter fullscreen mode Exit fullscreen mode

Let's make its polyfill

Array.prototype.ourFilter = function (callBack) {
  let output = [];
  for (let i = 0; i < this.length; i++) {
    if (callBack(this[i])) {
      output.push(this[i]);
    }
  }
  return output;
};

console.log(logicAlbums.ourFilter(greaterThan));
// console
// [ 
// {name: "Bobby Tarantino", rating: 5},
// {name: "Supermarket", rating: 4.9},
// {name: "Under Pressure", rating: 5}
// ]
Enter fullscreen mode Exit fullscreen mode

reduce

reduce() function is used to reduce the array to a single value.

not the exact definition, but we will consider this for sake of simplicity

const numbers = [1, 2, 3, 4, 5, 6];

function additionFunction(accumulator, current) {
  accumulator = accumulator + current;
  return accumulator;
}

const sum = numbers.reduce(additionFunction, 0);

console.log(sum);

// console
// 21
Enter fullscreen mode Exit fullscreen mode

Let's make its polyfill

Array.prototype.ourReduce = function (callback, initialValue) {
  var accumulator = initialValue === undefined ? undefined : initialValue;

  for (var i = 0; i < this.length; i++) {
    if (accumulator !== undefined) {
      accumulator = callback.call(undefined, accumulator, this[i], i, this);
    } else {
      accumulator = this[i];
    }
  }
  return accumulator;
};

console.log(numbers.ourReduce(additionFunction));

// console
// 21
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
tarunsahnan profile image
Tarun Sahnan • Edited

Here's a simplified version of reduce, in case you found accumulator = callback.call(undefined, accumulator, this[i], i, this); difficult to understand:

Array.prototype.myReduce = function(cb, initialValue) {
    let startIndex = initialValue !== undefined ? 0 : 1;
    let res = initialValue || this[0] || 0

    for (let i = startIndex; i < this.length; i++) {
        res = cb(res, this[i], i, this);
    }

    return res;
};

Enter fullscreen mode Exit fullscreen mode
Collapse
 
ganeshshetty195 profile image
Ganesh Shetty

Well written article

Collapse
 
azadtom profile image
Azadkumar

great article 👍

Collapse
 
khushbooraikwar95 profile image
Khushboo Raikwar

Awesome Explanation !

Collapse
 
ganeshshetty195 profile image
Ganesh Shetty
const numbers = [1, 2, 3, 4, 5, 6];
function callBack(acc,cur){
    return acc+cur;
}
Array.prototype.myReduce=function(cb,initial){
    let acc=initial!== 'undefined ' ?  initial :  this[0];
    console.log(acc);
    for(i=0;i<this.length;i++){
        acc = cb(acc,this[i]);
    }
    return acc;
}

console.log(numbers.myReduce(callBack,0));

Enter fullscreen mode Exit fullscreen mode
Collapse
 
hamza777 profile image
Hamza

accumulator = callback.call(undefined, accumulator, this[i], i, this);

Can you explain this line in a little detail, I find it a little difficult to grasp.
On MDN it says that the first arg passed to call is supposed to be thisArg (The value to use as this when calling func.) but you have passed undefined here.

Collapse
 
ganeshshetty195 profile image
Ganesh Shetty

It has to be object, only when you want that to be bound with that particular object,