Higher-order functions are functions that operate on other functions, either by accepting them as arguments or by returning them as their results. This allows us to create an abstraction layer over actions, not just values.
The main advantages of this technique are abstraction, composition, code reusability and readability. Most of the 30 seconds of code snippets are built with higher-order functions in mind. They are small, easily digestible functions that are highly reusable and can be composed to create more complex logic.
That being said, we can take a look at an example, utilizing some very simple functions:
const add = (a, b) => a + b; const isEven = num => num % 2 === 0; const data = [2, 3, 1, 5, 4, 6]; const evenValues = data.filter(isEven); // [2, 4, 6] const evenSum = data.filter(isEven).reduce(add); // 12
In this example, we define two simple functions that we then use as callbacks in
Array.prototype.filter() to get the result we want. Both of these functions are higher-order functions. This allows us to create an abstraction layer for any action we might want to perform without having to rewrite how the filtering or reduction algorithm is to be applied every single time.
Written by Angelos Chalaris
If you want to keep in touch, follow me on GitHub or Twitter.