Polyfills for map, filter and reduce | JavaScript Interview

If you are preparing for JavaScript Interview, Frontend Interview or Backend Interview where most of the stuff is done using JavaScript, then there is a high possibility that you will be asked to implement your version(called Polyfill) of an inbuilt JS function like map, filter, etc.
What exactly is Polyfill and why is it asked?
A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or because the new version of the browser does not have that feature.
Coming to why is it asked, creating a polyfill demonstrates that you have a strong understanding of JavaScript's core concepts, including functions, prototypes, closures, and other language features. It also shows your ability to work with the language at an advanced level.
map function
The map function is used to transform each element of an array by applying a provided callback function. It creates a new array containing the results of applying the callback to each element of the original array.
// Syntax of map function
// Array.map((currVal, index, arr)=>{})
const arr=[1,2,3,4,5];
const sqArr=arr.map((item)=>item*item);
const multByIndex=arr.map((item,index)=>item*index);
In the above example, we can see that the map function takes a callbackFn. The function is executed for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:
currVal: The current element being processed in the array.
index: The index of the current element being processed in the array.
arr: The array
mapwas called upon.thisArg [Optional]: A value to use as
thiswhen executingcallbackFn.
Now let's write the polyfill for the map:
const arr=[1,2,3,4,5];
Array.prototype.myMap=function(cb){
let temp=[];
for(let i=0;i<this.length;i++){
temp.push(cb(this[i],i,this));
}
return temp;
}
const newArr=arr.myMap((item,index)=>item*index);
const sqArr=arr.myMap((item)=>item*item);
console.log(newArr);
console.log(sqArr);
Code Breakdown:
An array
arris created with values[1, 2, 3, 4, 5].The
myMapmethod is added to theArrayprototype. This method takes a callback functioncbas its argument.Inside the
myMapmethod:A temporary array
tempis created to store the transformed values.A loop goes through each element of the array.
The callback function
cbis applied to each element, along with its index and the original array. The result is added to thetemparray.The
temparray is returned.
The results are logged into the console.
filter function
The filter function is used to create a new array containing only the elements that pass a certain condition specified by the provided callback function.
// Syntax of filter function
// array.filter((currentValue, index, arr)=>{});
const words = ['Hello', 'World', '!', 'How', 'Are', 'You'];
const result = words.filter((word) => word.length > 6);
console.log(result);
In the above example, we can see that the filter function takes a callbackFn. This function is executed for each element in the array. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise. The function is called with the following arguments:
currVal: The current element being processed in the array.
index: The index of the current element being processed in the array.
arr: The array
filterwas called upon.thisArg [Optional]: A value to use as
thiswhen executingcallbackFn.
Now let's write the polyfill for the filter function:
const words = ['Hello', 'World', '!', 'How', 'Are', 'You'];
Array.prototype.myFilter=function(cb){
let temp=[];
for(let i=0;i<this.length;i++){
if(cb(this[i],i,this)){
temp.push(this[i]);
}
}
return temp;
}
const result = words.myFilter((word) => word!=="!");
console.log(result);
Code Breakdown:
An array of
wordsis defined by several words.The
myFiltermethod is added to theArrayprototype. This method takes a callback functioncbas its argument.Inside the
myFiltermethod:A temporary array
tempis created to store the filtered values.A loop iterates over each element of the array.
The callback function
cbis applied to each element, and if the result istrue, the element is added to thetemparray.The
temparray containing filtered values is returned.
The
myFiltermethod is used with a callback that checks if a word is not equal to"!".The filtered result is logged into the console.
reduce function
The reduce function is used to "reduce" an array to a single value by applying a callback function to each element, accumulating a result along the way.
// Syntax of reduce function
// array.reduce((total, currValue, currIndex, arr)=>{}, initialValue)
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum);
In the above example, we can see that the reduce function takes a callbackFn. This function is executed for each element in the array. Its return value becomes the value of the accumulator parameter on the next invocation of callbackFn. For the last invocation, the return value becomes the return value of reduce(). The function is called with the following arguments:
currValue: The value of the current element. On the first call, the value of
array[0]if aninitialValuewas specified, otherwise the value ofarray[1].accumulator: The value resulting from the previous call to
callbackFn. On the first call,initialValueif specified, otherwise the value ofarray[0].index: The index position of
currentValuein the array. On the first call,0ifinitialValuewas specified, otherwise1.arr: The array
reducewas called upon.initialValue [Optional]: A value to which
accumulatoris initialized the first time the callback is called. IfinitialValueis specified,callbackFnstarts executing with the first value in the array ascurrentValue. IfinitialValueis not specified,accumulatoris initialized to the first value in the array, andcallbackFnstarts executing with the second value in the array ascurrentValue.
Now let's write the polyfill for the reduce function:
const numbers = [1, 2, 3, 4, 5];
Array.prototype.myReduce=function(cb,initialValue){
let accumulator=initialValue;
for(let i=0;i<this.length;i++){
accumulator=accumulator?cb(accumulator,this[i],i,this):this[i];
}
return accumulator;
}
const sum = numbers.myReduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum);
Code Breakdown:
An array
numbersare defined:[1, 2, 3, 4, 5].A custom
myReducefunction is added to theArrayprototype:It takes two arguments:
cb(callback function) andinitialValue.An
accumulatoris initialized with the value ofinitialValue.A loop iterates over the array elements.
For each element, the
cbfunction is called with argumentsaccumulator,this[i](current element),i(index), andthis(original array). The result is assigned to theaccumulator.The
accumulatoris returned after the loop.
Using
myReduceto calculate the sum:The
myReducefunction is used on thenumbersarray.The callback function
(accumulator, currentValue) => accumulator + currentValueadds the current value to the accumulator.An initial value of
0is provided for the accumulator.
The
sumis logged to the console.
We have written polyfill for map, filter, and reduce. 👏
In the upcoming blog, we will be learning about Promises and difference between all of its methods.
Thanks for reading🙂




