Higher-Order Functions

Functions that take or return other functions -- the vocabulary of composition, decoration and pipelines.

Syntaxconst decorate = (fn) => (...args) => { /* extra */ return fn(...args); }; const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);

A higher-order function either accepts a function as an argument, returns a function, or both. You already use them: map, filter, reduce, setTimeout, addEventListener.

The three moves that define real codebases

  • Compose -- glue small functions into a pipeline: compose(f, g)(x) === f(g(x)).
  • Decorate -- wrap a function to add behaviour (logging, timing, retry, throttle) without touching its body.
  • Return configured functions -- a factory that builds a validator, a formatter, a middleware.
const withLogging = (fn) => (...args) => {
  console.log('call', fn.name, args);
  return fn(...args);
};

These let you keep the core logic tiny and layer cross-cutting concerns as reusable wrappers.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Write a generic retry higher-order function that wraps any async operation with automatic back-off.
  • Build a memoize higher-order function that caches expensive computation results transparently.
  • Create a compose utility that chains multiple data-transformation functions into a single pipeline.

More examples

Function that accepts a function

applyTwice is a higher-order function that accepts a function and applies it twice to a value.

Example · js
function applyTwice(fn, x) {
  return fn(fn(x));
}
const increment = n => n + 1;
console.log(applyTwice(increment, 5)); // 7

Function that returns a function

withLogging wraps any function to log its arguments and return value, a classic HOF decorator pattern.

Example · js
function withLogging(fn) {
  return function (...args) {
    console.log("Calling with", args);
    const result = fn(...args);
    console.log("Result:", result);
    return result;
  };
}
const loggedAdd = withLogging((a, b) => a + b);
loggedAdd(3, 4);

compose utility

Builds a right-to-left function composition utility and uses it to build a slug generator from three small functions.

Example · js
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const trim   = s => s.trim();
const lower  = s => s.toLowerCase();
const slug   = s => s.replace(/\s+/g, "-");
const toSlug = compose(slug, lower, trim);
console.log(toSlug("  Hello World  ")); // "hello-world"

Discussion

  • Be the first to comment on this lesson.
Higher-Order Functions — JavaScript | SoundsCode