Polyfills for filter()

Omkesh B. Kendre
2 min readSep 27, 2021

--

What is Polyfill?

Polyfill is a piece of code (or plugin) that offers the functionality that you, the developer, would expect the browser to deliver natively. It’s a service that takes a request for a set of browser features and only delivers the polyfills the requesting browser requires.

filter()

The filter() method in JavaScript builds an array by filtering each element in the parent array with the help of conditions.

In general, the filter() method is used to filter (select) an array and call a function on each of the array’s elements.

The filter() method returns a new array containing all elements that pass the specified function’s test.

// Arrow function

filter((element) => {

} )

filter((element, index) => {

} )

filter((element, index, array) => {

} )


// Callback function

filter(callbackFn)

filter(callbackFn, thisArg)


// Inline callback function

filter(function callbackFn(element) {

})


filter(function callbackFn(element, index) {

})

filter(function callbackFn(element, index, array){

})
filter(function callbackFn(element, index, array) {

}, thisArg)

filter() was added to ECMA script in the 5th edition.

Polyfills for filter()

Array.filter() has only one argument, which is a callback function, which has three arguments: current value, index, and original array. As a result, we are taking care of those arguments while creating polyfill for filter().

Let’s use the above information to develop a polyfill for filter().

Array.prototype.myFilter = function(callback, context){

var arr = [];

for(i=0; i< this.length; i++){
if(callback.call(context, this[i], i, this)){

arr.push(this[i])
}
}
return arr;
}

const arrData = [0,1,2,3,4,5,6,7,8,9];


arrData.myFilter((element) => {

return ( element % 2 === 0 )

})

With the aid of the filter polyfill function, the preceding code generates an even numbers array (filter arrData for even numbers only).

--

--