What is the definition of a higher-order function in JavaScript?
TL;DR
A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result.
Higher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is Array.prototype.map(), which takes an array and a function as arguments. Array.prototype.map() then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are Array.prototype.forEach(), Array.prototype.filter(), and Array.prototype.reduce(). A higher-order function doesn't just need to be manipulating arrays as there are many use cases for returning a function from another function. Function.prototype.bind() is an example that returns another function.
Imagine a scenario where we have an array of names that we need to transform to uppercase. The imperative way will be as such:
Using Array.prototype.map(transformerFn) makes the code shorter and more declarative.
Higher order functions
A higher-order function is a function that takes another function as an argument or returns a function as its result.
Functions as arguments
A higher-order function can take another function as an argument and execute it.
In this example, the greetName function is a higher-order function because it takes another function (greet) as an argument and uses it to generate a greeting for the given name.
Functions as return values
A higher-order function can return another function.
In this example, the multiplier function returns a new function that multiplies any number by the specified factor. The returned function is a closure that remembers the factor value from the outer function. The multiplier function is a higher-order function because it returns another function.
Practical examples
- Logging decorator: A higher-order function that adds logging functionality to another function:
The withLogging function is a higher-order function that takes a function fn as an argument and returns a new function that logs the function call before executing the original function.
- Memoization: A higher-order function that caches the results of a function to avoid redundant computations:
The memoize function is a higher-order function that takes a function fn as an argument and returns a new function that caches the results of the original function based on its arguments.
- Lodash: Lodash is a utility library that provides a wide range of functions for working with arrays, objects, strings, and more, most of which are higher-order functions.
Further reading
- Higher-Order Functions
- Understanding Higher-Order Functions in JavaScript
- Higher Order Functions: How to Use Filter, Map and Reduce for More Maintainable Code