While going through Eloquent Javascript (Chapter 6) there is a reference to higher-order functions in Javascript. While there is an example provided in Chapter 3, I believe it could be a bit simpler since I still don’t fully understand the concept. After searching the web I can’t seem to find any succinct examples of a higher-order function.
I’d like to see a basic/simple higher-order function in Javascript that will explain the concept.
Higher functions are concepts from functional programming. In briefly, a higher function is a function which takes another function as parameter. In javascript, some higher functions are added recently.
So, in the above sample,
reduceis a higher order function, it takes another function, the anonymous function in the sample, as a parameter. The signature ofreducelooks like thisAs you can see,
reduceiterate an array, and apply thefuncwithinitand first element of that array, then bind the result toinit.Another higher order funciton is
filter.With the above two examples, I have to say higher order function is not that much easy to understand, especially
reduce. But that’s not complex, with higher order function, actually your code would be more clean and readable. Take thefilteras example, it tells people that it throws all odd numbers away.Here I’d like to implement a simple
filterfunction to show you how.