JavaScript Tutorials

Filter() vs Find() Using JavaScript Array Explained!

Last modified on June 12th, 2022
Javascript

The filter() function will get all the elements from an array as long as the provided condition is met.

It’ll return a new array just with filtered elements.

The find() function will get only the very first element as soon as the provided condition is met and ignores everything else. It’ll return just that element.

That’s simple eh!

Let’s see that in action

Filter()

When we loop through a JavaScript array using filter() function.

It’ll search and get all the elements that meet a specific condition in that array.

Then, it will return them as a new array.

And the output will be [20, 25].

const ages = [3, 10, 18, 20, 25];

const foundItems = ages.filter(age => {
  return age > 18;
});

console.log(foundItems); // [20, 25]

Find()

On the other hand, find() function will only return the very first element that meets the provided condition and ignores everything else from a JavaScript array.

And the output will be 20.

const ages = [3, 10, 18, 20, 25];

const found = ages.find(age => {
  return age > 18;
});

console.log(found); // 20

Recommended