High-Order functions are good and you should use them

High order functions (or functors) are essentialy any functions which receives one or more functions as parameters or return one function as its result.

But why you should care?

You should care about them because they are implemented as many useful methods that makes your every day as a developer a little bit easier:

Let’s assume we have the following array:

And now, we want to get all the even elements:

Let’s take a close look at this loop:

  • At line 2, me must know what is our array size
  • At line 3, we need to create a new element to handle our current value
  • At line 1 and 5, we create and populate a new array with our loop results
  • About the general code, how much time will someone other than you need to understand what are you doing in this for loop?

It’s a simple loop, but it gives us a lot of chances for commiting mistakes that we can avoid by simply using our language tools:

Or using some ES6 features:

Taking another close look at our code, we can see that this is a handsomer code than the for loop, right? There’s not much room to commit mistakes, and anyone who bats an eye in your code will easily understand that you are filtering an array and getting the elements which are divisible by 2.

So, you loved high order functions but you have no idea about how to implement one?
Let’s create our own “filter” function:


Now that i’ve convinced you that you will be very happy while using High-Order functions, take a look at some of them at MDN Array.prototype.map, Array.prototype.reduce, Array.prototype.filter