Functions
Higher-order functions
Functions that take or return other functions.
A higher-order function either takes a function as an argument, returns a function, or both. They are the foundation of functional programming in JavaScript.
A higher-order function is a manager who either delegates work to a hired specialist (callback) or hires and hands you a new specialist (returned function).
Key concepts
1
You use them constantly: map, filter, reduce, setTimeout and event listeners all accept callbacks. Returning functions enables factories, decorators and middleware.
mapfilterreducesetTimeout
2
Treating functions as first-class values — passing them around like any other data — is what makes patterns like debounce, memoize and compose possible.
first-class values
javascript
// Takes a function
const withLogging = fn => (...args) => {
console.log('calling with', args);
return fn(...args);
};
const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(2, 3); // logs then returns 5