A higher-order function (HOF) is a function that accepts a function, returns a function, or does both. JavaScript allows this because functions are first-class: in the spec they are objects (typeof gives "function", and they have [[Call]]), so they can be assigned to variables, passed as arguments, and returned like any value.
Two shapes cover almost everything:
- Takes a function (a callback).
Array.prototype.map/filter/reduce/sort,setTimeout,addEventListener,Promise.prototype.then. The HOF decides when and with what to call your function; you decide what it does. - Returns a function (a function factory or decorator).
debounce(fn),once(fn),fn.bind(...),compose(f, g). The returned function remembers its inputs through a closure.
Why they matter: they separate the iteration or control-flow policy from the per-item logic, and they let you add behaviour (logging, caching, retries) around a function without editing it.
When writing a wrapper, forward everything: arguments (...args), the return value, and this (fn.apply(this, args)). Know what the HOF passes to your callback: map calls it with (element, index, array), which is why passing a function that takes extra optional parameters can misbehave.