Yes, a function can return another function. This is known as higher-order functions and it’s a fundamental part of functional programming. It allows for the creation of abstract operations that can be reused with different functions, enhancing code reusability and modularity.
For instance, consider a scenario where we need to apply several transformations to an array of data. Instead of creating separate functions for each transformation, we could create a higher-order function that takes in the specific transformation function as an argument and applies it to the array.
Here’s a simple JavaScript example:
function createMultiplier(multiplier) {
const double = createMultiplier(2);
console.log(double(5)); // Outputs: 10
In this case,
createMultiplier
is a higher-order function that returns a new function. The returned function multiplies its input by the
multiplier
parameter from the outer function. This approach provides flexibility as we can easily create other multiplier functions like triple, quadruple etc., without repeating code.