Higher-order functions

Topic 6 of 6 in Functions6 min readBeginnerFree course

Overview

In JavaScript, functions are values like numbers or strings — programmers say functions are first-class. You can store them in variables, put them in arrays and objects, pass them to other functions and return them.

JavaScript
const sayHi = () => console.log('Hi');
const actions = [sayHi, () => console.log('Bye')];
const handlers = { greet: sayHi };

actions[1]();     // 'Bye'
handlers.greet(); // 'Hi'

A higher-order function is one that takes a function as an argument, returns a function, or both.

Top: a function () => log(“Hi”) is passed in to twice(action), which calls it two times, printing Hi twice. Bottom: multiplier(2) returns the function (n) => n * factor with factor = 2 remembered; saved as double, double(5) gives 10.

Taking a function

JavaScript
function twice(action) {
  action();
  action();
}

twice(() => console.log('Hello!'));

twice doesn’t know or care what the action is — it only decides how many times to run it. You’ve already used this idea with setTimeout and addEventListener.

A function passed into another function is called a callback: the higher-order function “calls it back” at the right moment.

Passing a named function

You can pass any function, not just arrow functions written in place. Pass the name without brackets — you’re handing over the function itself, not calling it:

JavaScript
function logRound(i) {
  console.log(`Round ${i}`);
}

repeat(3, logRound);    // ✓ pass the function
repeat(3, logRound());  // ✗ calls it now and passes its result (undefined)

Why bother?

Higher-order functions remove repetition. Imagine three loops that differ only in what they do with each item:

JavaScript
for (const p of prices) console.log(p);
for (const p of prices) total += p;
for (const p of prices) if (p > 100) expensive.push(p);

The looping is the same every time; only the action changes. Pull the loop into a function and pass the action in:

JavaScript
function each(list, action) {
  for (const item of list) action(item);
}

each(prices, (p) => console.log(p));
each(prices, (p) => { total += p; });

That’s exactly what the built-in forEach does.

Returning a function

JavaScript
function multiplier(factor) {
  return (n) => n * factor;
}

const double = multiplier(2);
const triple = multiplier(3);
double(5); // 10
triple(5); // 15

Each returned function remembers its own factor — a closure.

Returning functions lets you configure behaviour once and reuse it:

JavaScript
function greaterThan(limit) {
  return (n) => n > limit;
}

const prices = [120, 80, 45, 300];
prices.filter(greaterThan(100)); // [120, 300]
prices.filter(greaterThan(50));  // [120, 80, 300]

Wrapping functions

A higher-order function can take a function and return a new one that adds something extra, such as logging or timing:

JavaScript
function withLogging(fn) {
  return (...args) => {
    console.log(`Calling with`, args);
    const result = fn(...args);
    console.log(`Result:`, result);
    return result;
  };
}

const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(2, 3); // logs the arguments and the result, returns 5

The once and memoize helpers in the Closures topic are wrappers too.

Built-in examples

Arrays come with many higher-order methods:

JavaScript
const prices = [120, 80, 45];
prices.map((p) => p * 1.18);        // add tax to each
prices.filter((p) => p > 50);       // keep some
prices.some((p) => p > 100);        // true
prices.every((p) => p > 10);        // true
prices.find((p) => p < 100);        // 80
prices.sort((a, b) => a - b);       // [45, 80, 120]
prices.forEach((p) => console.log(p));

Each method handles the looping; your callback says what to do with each item. You’ll study map, filter and reduce in their own topic.

Outside arrays, you’ll meet higher-order functions everywhere:

JavaScript
setTimeout(() => console.log('Later'), 1000);
button.addEventListener('click', handleClick);
fetch(url).then((response) => response.json());

Composing functions

Small, single-purpose functions can be combined into bigger ones:

JavaScript
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const dashes = (s) => s.replaceAll(' ', '-');

function pipe(...fns) {
  return (input) => fns.reduce((value, fn) => fn(value), input);
}

const toSlug = pipe(trim, lower, dashes);
toSlug('  Higher Order Functions '); // 'higher-order-functions'

pipe takes functions and returns a function — a higher-order function in both directions.

Name your callbacks when they grow. prices.filter(isAffordable) reads better than a five-line arrow function in the middle of a call.

Exercise

Repeat an action

Write repeat(n, action) that calls action(i) for each i from 0 to n - 1. Then write not(fn) that returns a new function giving the opposite boolean of fn.

JavaScript
function repeat(n, action) {
  // your code here
}

function not(fn) {
  // your code here
}

repeat(3, (i) => console.log(`Round ${i}`));
const isOdd = not((n) => n % 2 === 0);
isOdd(3); // true

Summary

  • Functions are values: store them, pass them, return them.
  • A higher-order function takes a function as an argument or returns one.
  • A function passed in is called a callback; pass it without brackets.
  • They let you separate *what* to do from *how often* or *when*.
  • Array methods like map, filter, sort and forEach are higher-order functions.