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
map
was called upon.thisArg [Optional]: A value to use as
this
when 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
arr
is created with values[1, 2, 3, 4, 5]
.The
myMap
method is added to theArray
prototype. This method takes a callback functioncb
as its argument.Inside the
myMap
method:A temporary array
temp
is created to store the transformed values.A loop goes through each element of the array.
The callback function
cb
is applied to each element, along with its index and the original array. The result is added to thetemp
array.The
temp
array 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
filter
was called upon.thisArg [Optional]: A value to use as
this
when 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
words
is defined by several words.The
myFilter
method is added to theArray
prototype. This method takes a callback functioncb
as its argument.Inside the
myFilter
method:A temporary array
temp
is created to store the filtered values.A loop iterates over each element of the array.
The callback function
cb
is applied to each element, and if the result istrue
, the element is added to thetemp
array.The
temp
array containing filtered values is returned.
The
myFilter
method 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 aninitialValue
was specified, otherwise the value ofarray[1]
.accumulator: The value resulting from the previous call to
callbackFn
. On the first call,initialValue
if specified, otherwise the value ofarray[0]
.index: The index position of
currentValue
in the array. On the first call,0
ifinitialValue
was specified, otherwise1
.arr: The array
reduce
was called upon.initialValue [Optional]: A value to which
accumulator
is initialized the first time the callback is called. IfinitialValue
is specified,callbackFn
starts executing with the first value in the array ascurrentValue
. IfinitialValue
is not specified,accumulator
is initialized to the first value in the array, andcallbackFn
starts 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
numbers
are defined:[1, 2, 3, 4, 5]
.A custom
myReduce
function is added to theArray
prototype:It takes two arguments:
cb
(callback function) andinitialValue
.An
accumulator
is initialized with the value ofinitialValue
.A loop iterates over the array elements.
For each element, the
cb
function is called with argumentsaccumulator
,this[i]
(current element),i
(index), andthis
(original array). The result is assigned to theaccumulator
.The
accumulator
is returned after the loop.
Using
myReduce
to calculate the sum:The
myReduce
function is used on thenumbers
array.The callback function
(accumulator, currentValue) => accumulator + currentValue
adds the current value to the accumulator.An initial value of
0
is provided for the accumulator.
The
sum
is 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🙂