A higher-order function is a function that takes another function as an argument, returns a function, or both.
This is possible because functions in JavaScript are first-class values. You can store them in variables, pass them around and return them, like any other value.
Examples that take a function:
Array.prototype.map,filterandreducesortwith a compare functionsetTimeoutaddEventListener
Examples that return a function:
debounce,memoizeandcurryFunction.prototype.bind- factories like
const multiplier = n => x => x * n
In React, higher-order components and custom hooks that return callbacks use the same idea.
Higher-order functions let you reuse behaviour, not just values. This removes duplicate code. For example, the looping logic lives inside map, and you only supply the part that changes.
- A higher-order function takes a function as an argument, returns one, or both.
- It works because functions are first-class values in JavaScript.
- Built-in examples are
map,filter,reduce,setTimeoutandaddEventListener. - Examples that return functions are
bind,debounce,memoizeand factories.
Read more