The Art of Array Manipulation: Exploring JavaScript’s Array.prototype.filter() method.

Prathm
Stackademic
Published in
7 min readNov 25, 2023

--

The methods such as Array.prototype.filter(), Array.prototype.map() and Array.prototype.reduce() are essential to the JavaScript functional programming paradigm. I would ask you this: Do you really understand how filter method operate on the inside? I won’t get into the implementation per se; instead, let’s explore how it work behind the scenes. Like with all of my blogs, I emphasize the saying “the Devil is in the details.” Now dig deep and will try to find that devil (pun intended) of the JavaScript language. Oh my goodness, I’m really excited right now. Are you?”

In javascript arrays are not “primitive values” but caregtorize as a “object” and when we say object the other word comes to our mind is “method” and for this blog I want to divert your focus to Non-Mutating and Mutating methods of the array. Basically if I want to tell the difference in simple manner I would say, the methods which do not mutate the original array but instead they produce or return a new array with necessary changes are called as Non-Mutating methods and Mutating methods are those one, which mutate the original array.

Array.prototype.filter() is one of the Non-Mutating method which returns the new array. The return array contains the elements which are filtered from the original array on basis of the test implemented by the callback function passed as an input argument to the .filter() method.

The signature of “filter” method is as follows:

As you can see there are two parameters callbackfn and thisArg (thisArg is an optional parameter).

Lets discuss about first paramter i.e callbackfn:

First parameter is a callback function which executes for each element in an array and it should return truthy value to keep the element into resulting new array and falsy value for otherwise.

The callback function takes following arguments:

Lets see what those parameter are:

  1. element -> The current element of the array, on which the filter method is called upon.
  2. indexOfElement -> The index of the currentElement which is processed by the callback function.
  3. array -> The array on which filter method is called.

Now since you understand the filter method signature (Signature is nothing but the information about the parameters passed in it.)

Lets take a quick look on the implementation of the .filter method:

Here I am trying to filter out the even numbers from the array identified as “numbers”. So I called filter method on “numbers” and passed one callback function identified as “filterEven”. This callback function executes on every element of the array and check for the condition. In this case the condition is num % 2 === 0.

So whichever element will pass the test will get the gate pass to enter into new array and whichever fails will sadly never enter into array returned by the filter method. So this is how the filter method works.

Why to use Array.prototype.filter() method, Can’t you achieve the filtering using forEach or something similar like it??:

Let’s filter even numbers from array using forEach:

Have you seen what I have done in above code snippet,

I defined an empty array as “filteredArray”, then I called forEach method on “numbers” array and passed one callback function “filterEven” into forEach. Which will execute on every element of the numbers array. The callback function contains one “ if clause”, Which checks if the number is even or not and if it is even then it will push the number into the new array identified as “filteredArray”.

Let me tell you why we use filter method even if we can achieve same filtering using forEach method as well.

  1. Reliability and Expressivness: The filter method is defined specifically for the purpose of filtering elements based on condition defined in callback function, It clearly communicate the intent of filtering to other developers so easy to maintain the code.
  2. Conciseness: The filter method is lot more concise than the forEach.
  3. Immutability: The “filter” method returns a new array containing only the elements that pass the provided test. This promotes immutability, which is a key principle in functional programming. It means you're not modifying the original array but creating a new one with the desired elements.
  4. Chaining: Because “filter” returns a new array, you can easily chain it with other array methods like “map”, “reduce”, or “forEach” to perform a sequence of operations in a more elegant and concise way.

Now it’s time to see how the Array.prototype.filter() method works behind the scene:

Whoooooo!! What’s this…..??.

The above code snippet depicts one of the way of creating our own filter() method

I will try simplify things line by line:

This condition is nothing but another way of saying if(true).

Here we are redefining Array.prototype.filter method with our custom function which takes two argumnets:

  1. Callback function
  2. thisArg → thisArg is nothing but an array on which our filter method is going to run. Consider one example, there is an array named as “numbers ” and you will run a filter() method on it then, it would look something like, “numbers.filter()” so in this case “thisArg” would be equal to “numbers”.

Just to double checking that we are not running the default filter method given by javascript.

Here “this” will be an array on which we are calling the filter method and we are checking the array should not be null or undefined. If it is then we are throwing new TypeError.

In this line we are checking the callback we are passing must be an function and nothing else.

Creating an empty array which will be returned by the filter method.

Here “this” is nothing but array on which filter method is going to run. (as told earlier) we are running a forEach on array where forEach taking a callback function named “processEachElement” as its input argument. Let’s have a look on that callback function named as “processEachElement”:

This is the same function which we pased as a callback to forEach method.Function is taking three input parameters which are self explanatory. But what I want you to focus on is “if ” clause inside of the function.

Here we are calling the callback function (which we passed as input argument to filter method) with “call” method we are binding the “this” of the callback function with “thisArg” (which is nothing but an array on which we are running the filter method), after “thisArg” parameter, we are forwarding the same parameters which are passed to the forEach callback function “processEachElemet”.

The callback function return truthy or falsy values. So if return value of the callback function (in if clause) is true. We will push the element into the filteredArray.

and finally we will return the filteredArray

So this is how you can create your own filter function.

I hope you had fun diving into the magic behind the scenes of the filter method! If you found this journey interesting, don't forget to hit that like button, share with your fellow coders, and maybe even consider hitting that follow button for more coding adventures. Until next time, happy coding and see you in the next one!

Happy Coding!

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X), LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.

--

--

Dedicated JavaScript & React developer, tech enthusiast, forever exploring.