DEV Community

Nitesh Patel
Nitesh Patel

Posted on • Edited on

Polyfills in JS - Interview Questions

Here are five important polyfills in javascript. I will be covering forEach, map, filter, reduce, flat in the easiest way possible.

NOTE : Knowledge of the This keyword is crucial.

Let's get started!

  • forEach

The code below is a simple example of forEach.

const numbers = [1, 2, 3, 4, 5] const ans = numbers.forEach((n) => console.log(n)) 
Enter fullscreen mode Exit fullscreen mode

polyfill of forEach

const numbers = [1, 2, 3, 4, 5] Array.prototype.myForEach = function (callbackfn) { for (let index = 0; index < this.length; index++) { callbackfn(this[index], index, this) } } numbers.myForEach((n) => console.log(n)) 
Enter fullscreen mode Exit fullscreen mode
  • map

Simple example of in-built mapfunction

const numbers = [1, 2, 3, 4, 5] console.log(numbers.map((n) => n * 2)); 
Enter fullscreen mode Exit fullscreen mode

Here is polyfill of map

const numbers = [1, 2, 3, 4, 5] Array.prototype.myMap = function myMap(cb) { const output = [] for (let i = 0; i < this.length; i++) { let a = cb(this[i]) output.push(a) } return output } console.log(numbers.myMap((n) => n * 2)); 
Enter fullscreen mode Exit fullscreen mode
  • filter

Here is filterexample

const numbers = [1, 2, 3, 4, 5] console.log(numbers.filter((n) => n > 3)); 
Enter fullscreen mode Exit fullscreen mode

Polyfill of filter

const numbers = [1, 2, 3, 4, 5] Array.prototype.myFilter = function (cb) { const output = [] for (let i = 0; i < this.length; i++) { if (cb(this[i])) { output.push(this[i]) } } return output } console.log(numbers.myFilter((n) => n > 4)); 
Enter fullscreen mode Exit fullscreen mode
  • reduce

example of reducemethod

const numbers = [1, 2, 3, 4, 5] console.log(numbers.reduce((acc, curr) => { return acc + curr }, 0) ); 
Enter fullscreen mode Exit fullscreen mode

polyfill of reduce

const numbers = [1, 2, 3, 4, 5] Array.prototype.myReduce = function (cb, initialValue) { let acc = initialValue; for (let i = 0; i < this.length; i++) { acc = acc ? cb(acc, this[i]) : this[i] } return acc } console.log(numbers.myReduce((acc, curr) => { return acc + curr }, 1)); 
Enter fullscreen mode Exit fullscreen mode
  • flat

Example of flatmethod, it takes depth as an argument. Depth refers to how deeply nested arrays within the original array should be flattened.

const numbers = [1, [2, [3, 4]]] console.log(numbers.flat(2)); 
Enter fullscreen mode Exit fullscreen mode

polyfill of flat

const numbers = [1, [2, [3, 4]]] Array.prototype.myflat = function (depth) { const output = [] if (!Array.isArray(this)) { throw new Error(`${this}.flat is not a function`); } this.forEach((n) => { if (Array.isArray(n) && depth > 0) { output.push(...n.myflat(depth - 1)) } else { output.push(n) } }); return output } console.log(numbers.myflat(2)); 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)