A higher-order function is a function that does at least one of the following:
- Takes one or more functions as arguments
- Returns a function as its result
Higher-order functions are some of the most powerful tools that we can use to write JavaScript in a functional programming style. Let's look at some examples.
The following code snippet declares a function named addDelay. The function creates a new function that waits for a given number of milliseconds before printing a message in the console. The function is considered a higher-order function because it returns a function:
function addDelay(msg: string, ms: number) {
return () => {
setTimeout(() => {
console.log(msg);
}, ms);
};
}
const delayedSayHello = addDelay("Hello world!", 500);
delayedSayHello(); // Prints "Hello world!" (after 500 ms)
The following code snippet declares a function named addDelay. The function creates a new function that adds a delay in milliseconds to the execution of another function that is passed as an argument. The function is considered a higher-order function because it takes a function as an argument and returns a function:
function addDelay(func: () => void, ms: number) {
return () => {
setTimeout(() => {
func();
}, ms);
};
}
function sayHello() {
console.log("Hello world!");
}
const delayedSayHello = addDelay(sayHello, 500);
delayedSayHello(); // Prints "Hello world!" (after 500 ms)
Higher-order functions are an effective technique for abstracting a solution for a common problem. The preceding example demonstrates how we can use a higher-order function (addDelay) to add a delay to another function (sayHello). This technique allows us to abstract the delay functionality and keeps the sayHello function, or other functions, agnostic of the implementation details of the delay functionality.