Explain forEach, map, filter, and for example, Polyfill

These four are array methods.

Polyfill

If the browser has a fallback of any method or features. then we write Polyfill. It is a just piece of code to apply modern features or functionality to old browsers.

forEach()

  • Just like for loop

  • It is used to iterate over an array.

  • It takes a callback function and calls once for every element in the array.

  • It does not return anything.

const array = [4, 6, 7, 8, 9, 10]

array.forEach((cb) => console.log(cb)) 

// 4
// 6
// till 10

Polyfill for forEach()

// for each just like for loop
// it does not return an any array
// it is use for iteration
Array.prototype.myForEach = function (callback) {
  for (let i = 0; i < this.length; i++) {
    callback(this[i], i, this);
  }
};

 array.myForEach((cb) => console.log(cb))

// 4
// 6
// till 10

map()

  • It is used to iterate over an array.

  • It takes a callback function and calls once for every element in the array.

  • and return a new array.

const array = [4, 6, 7, 8, 9, 10]
const newArray = array.map((cb) => cb * 2) 
console.log(newArray) // [8, 12, 14, 16, 18, 20 ]

Polyfill for map()

Array.prototype.myMap = function (callback) {
  let newArray = [];

  // Here this is the source array 
  for (let i = 0; i < this.length; i++) {
    newArray[i] = callback(this[i], i, this);
  }

  return newArray;
};

const result = array.myMap((cb) => cb * 2);
console.log(result) // // [8, 12, 14, 16, 18, 20 ]

filter()

The filter method returns a new array of an element that passes a condition provided by the function.

const array = [4, 6, 7, 8, 9, 10]
const newArray = array.filter((cb) => cb > 7) 
console.log(newArray) // [8, 9, 10 ]

Polyfill of filter()

Array.prototype.myFilter = function (callback) {
  let newArray = [];

  for (let i = 0; i < this.length; i++) {
    if (callback(this[i], i, this)) {
      newArray.push(this[i]);
    }
  }

  return newArray;
};

// We are saying
const filterResult = array.myFilter((cb) => cb > 7);

console.log(filterResult); // [8, 9, 10 ]

Last updated