Topic 23 of 37
Higher-Order Functions
Overview
A Higher-Order Function (HOF) is a function that either takes one or more functions as arguments (callbacks) OR returns a function as its result. This is possible because functions in JS are First-Class Citizens (they can be treated like any other variable).
Syntax
withLogging wraps the original function, adding extra behavior. This is exactly how React Higher-Order Components (HOCs) work.
Taking and Returning Functions
javascript
// Takes a function as an argument
function withLogging(fn) {
// Returns a function (HOF)
return function(...args) {
console.log("Calling function with", args);
return fn(...args);
};
}
const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
console.log(loggedAdd(2, 3));
// Logs: "Calling function with [2, 3]"
// Returns: 5Common Pitfalls
- Forgetting to return the inner function from your Higher-Order Function, resulting in 'undefined is not a function' errors.
Interview Tips
- Be prepared to write a simple polyfill for .map() or .filter(), which are classic examples of Higher-Order Functions.
Real-World Example
Debouncing user input relies entirely on closures and higher-order functions.
example
javascript
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func(...args), delay);
};
}