This chapter follows The this keyword.
A higher-order function takes a function as an argument, returns a function, or both. JavaScript treats functions like any other value, so higher-order style is the default in modern code—not an advanced pattern.
Functions as values
Function declarations and expressions produce callable values you can assign and pass around.
const double = (n) => n * 2;const apply = (fn, x) => fn(x);
apply(double, 21); // 42Named function expressions are useful for recursion (const fact = function fact(n) { ... }).
Callbacks
A callback is a function passed to another function to run later—on an event, when I/O completes, or for each collection element.
document.addEventListener('click', (event) => { console.log(event.type);});The callee controls when and with what arguments the callback runs. Error-first Node-style callbacks (err, result) => {} and Promise .then(fn) are the same idea with different conventions.
Array higher-order methods
Built-ins encode common loops as higher-order calls:
| Method | Role |
|---|---|
map |
Transform each element |
filter |
Keep elements where predicate is true |
reduce |
Fold to one value |
find / some / every |
Search or test |
const ids = users .filter((u) => u.active) .map((u) => u.id);These methods do not mutate the array (unless your callback mutates elements). For async work over collections, use for...of with await or Promise.all with map.
Returning functions (factories)
Higher-order functions often configure behavior by closing over parameters:
function multiplyBy(factor) { return (n) => n * factor;}
const triple = multiplyBy(3);triple(4); // 12That pattern leads to currying, composition, and memoization in the next chapter.
Partial application versus bind
bind(null, arg1) fixes early arguments; a wrapper function can do the same with clearer types in TypeScript. Prefer small named functions when a one-off callback would be hard to test.