Learn/JavaScript/14. Closures and higher-order functions
Lesson 14 of 15
Sign in

JavaScript, lesson 14

Closures and higher-order functions

In JavaScript, functions are values, just like numbers and strings. You can store them in variables, put them in arrays, pass them to other functions and return them from functions. This one idea, together with closures, is behind much of the language's character, from array methods to event handlers.

Higher-order functions

A higher-order function takes a function as an argument or returns one. The array methods are the ones you will use every day:

const prices = [4, 12, 7, 30];

const withTax = prices.map((p) => p * 1.2);          // transform each element
const cheap = prices.filter((p) => p < 10);          // keep elements that pass a test
const total = prices.reduce((sum, p) => sum + p, 0); // combine into one value
const anyBig = prices.some((p) => p > 20);           // true if at least one passes
const allPositive = prices.every((p) => p > 0);      // true if all pass

console.log(cheap, total, anyBig, allPositive);      // [ 4, 7 ] 53 true true

reduce deserves a closer look. It walks the array carrying an accumulator. The callback receives the accumulator and the current element and returns the new accumulator. The second argument (0 here) is the starting value. Always give one; without it, reduce on an empty array throws.

These methods do not change the original array, and they chain nicely:

Each callback also receives the index as a second argument, as in forEach((item, i) => ...).

Closures

A function can use variables from the place where it was written. When an inner function outlives the outer function call, it keeps those variables alive. That combination of a function and the variables it remembers is a closure:

Every call to makeCounter creates a new count, so a and b each have their own. Nothing outside can touch count except through the returned function: closures give you private state without a class.

Function factories

Returning functions lets you build specialised functions from general ones:

You can also combine functions. pipe takes several functions and returns one that runs them in order, feeding each result into the next:

...fns is a rest parameter: it gathers all arguments into an array.

A closure pitfall

Closures capture the variable, not a snapshot of its value. With let in a for loop, each round gets a fresh variable, so callbacks created in the loop each see their own value. The old var keyword shares one variable across all rounds, and every callback would see the final value. One more reason to stick to let and const.

Further reading

  • MDN: Closures
  • MDN: Functions guide
  • MDN: Array.prototype.reduce
  • MDN: Rest parameters

2 exercises to try what you just read.

Exercise 1

Order summary

Each input line is an order: CUSTOMER AMOUNT STATUS, where status is paid or pending. Using filter, map and reduce (no for loops), print:

  • paid total: X: the sum of all paid amounts, with two decimals;
  • pending: N: how many orders are pending;
  • big spenders: ...: the distinct customers who have at least one paid order of 50 or more, in the order they first appear, separated by , (or none).

Sample input:

Sample output:

Press Ctrl Enter or Check to test your code.

Exercise 2

Function pipeline

Write two functions:

  • makeStep(name) returns a function for one of these step names: double (times 2), inc (plus 1), square (times itself), negate (change sign), or add:N (plus the number N, for example add:5 or add:-3). For add:N, the returned function must remember N; that is a closure.
  • pipe(...fns) returns a single function that applies all the given functions from left to right.

The program around them is written for you. The first input line lists step names separated by spaces; each following line is a starting number. For each number, the program prints the result of the whole pipeline.

Sample input:

Sample output:

For 1: double gives 2, add 3 gives 5, square gives 25.

Press Ctrl Enter or Check to test your code.

const report = prices
  .filter((p) => p >= 7)
  .map((p) => `$${p}`)
  .join(", ");                 // "$12, $7, $30"
function makeCounter() {
  let count = 0;               // private to this counter
  return () => {
    count += 1;
    return count;
  };
}

const a = makeCounter();
const b = makeCounter();
a(); a();
console.log(a(), b());         // 3 1
const multiplier = (factor) => (n) => n * factor;
const double = multiplier(2);
const triple = multiplier(3);
console.log([1, 2, 3].map(triple));   // [ 3, 6, 9 ]
const pipe = (...fns) => (x) => fns.reduce((value, fn) => fn(value), x);
const process = pipe(double, (n) => n + 1, String);
console.log(process(5));   // "11"
ana 20.50 paid
ben 75 paid
cy 99 pending
ben 60 paid
dee 50 paid
paid total: 205.50
pending: 1
big spenders: ben, dee
double add:3 square
1
-2
25
1