Pankaj Singh

Self-taught Web Developer

JavaScript’s Filter Function Explained

Compared to the map() and reduce() methods in JavaScript, the filter()method has probably the most straightforward name.


You input an array, and you filter out the elements that fulfill a specific condition into a new array.

This seems simple, but I always seemed to find myself reverting to for() loops. So, I decided to find a better way to understand how filter() functions worked.


I realized that filter functions are kind of like a college admissions officer. They use a set of parameters to decide which students should be admitted to their particular college. Yes, we all wish that colleges were a little more flexible and judged our accomplishments holistically, but in reality, most still have hard numbers around SAT, ACT and GPA scores that determine who will be considered.

Let’s get into it!


Using A For Loop Instead of Filter Function

Okay, let’s say that we have an array of 4 students with names and GPAs. This particular college only wants to admit students with a 3.2 GPA or higher. Here is how you might do that.


Using the Filter() Method

Let’s learn how to accomplish the same goal with the filter() method.


  1. Filter is an array method, so we will start with the array of students.
  2. It uses a callback function that runs on each element in the array.
  3. It uses a return statement to show which elements will actually end up in the final array, in this case, the admitted students.

The inputs and outputs are the same, so here’s what we did differently:

  1. We didn’t need to declare the admitted array and then fill it later. We declared it and then filled it with elements in the same code block
  2. We actually used a condition within the return statement! That means that we only return elements that pass a certain condition.
  3. We can now use student for each element in the array, rather than students[i] like we did in the for loop.

You may notice that one thing is counterintuitive- getting admitted to college is the last step, but in our code, the variable admitted is the first part of the statement! You might usually expect to find the final array as the last statement within the function. Instead, we use return to indicate which elements will end up in admitted.


Article By Pankaj Singh

Skilled in programming language JavaScript, comfortable with the latest versions ES6. Also having good Python knowledge with strong OOPs concept. Full Stack Developer using NodsJs/Django for Backend with CSS/HTML/JavaScript/MDBootstrap, API, MySQL,MongoDB,Github and Herokuapp. Analytical thinker that consistently resolves ongoing issues or defects, often called upon to consult on problem that have eluded resolution from others.

Discuss about post

Subscribe to my weekly newsletter

Read Also

How to make your company website based on bootstrap framework...