30 Days Of JavaScript

Day 10: Higher Order Functions Part 1

Lesson 4: filter

Next up is .filter() this does exactly what you would expect, filters an array based on whatever function you pass into it.

The function you pass into .filter() should return true if the item should be kept in the array and false if it should not be included.

Let's filter out people below 18 in this array:

Again, I've use the shorthand syntax here as it's very common when using higher order functions, the longer form version of this looks like this:

Change the age above to be older than the oldest person (so at least 33), what do you think you'll get back?

You get back an empty array.

Some people get confused by this. It's an empty array (rather than an error or warning) because an array with no items in it, is still a valid response from a filter. In this example if no number is larger than the one you filter by then an empty array is the correct response.

That's really all there is to filter.

Outline

Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co