Lesson 12 of 14 · 12 min

Closures and functions as values

In JavaScript, functions are values, like numbers and strings. You can store them in variables, pass them to other functions, and return them:

const shout = text => text.toUpperCase() + "!";

function twice(fn, value) {
  return fn(fn(value));
}

twice(x => x + 3, 1);  // 7

You have already done this: map, filter and reduce take functions as arguments. Functions that take or return functions are called higher-order functions.

Closures

A function remembers the variables that existed where it was created, even after that outer function has finished. This is a closure:

function makeGreeter(greeting) {
  return name => `${greeting}, ${name}!`;
}

const hello = makeGreeter("Hello");
const mhoro = makeGreeter("Mhoro");
hello("Ana");   // "Hello, Ana!"
mhoro("Tino");  // "Mhoro, Tino!"

Each returned function keeps its own greeting. Closures are how JavaScript keeps private state: nothing outside can reach greeting except through the function.

Your task

  1. makeCounter() returns a function. Each call to that function returns the next number: 1, then 2, then 3... Each counter keeps its own count.
  2. compose(f, g) returns a new function that, given x, returns f(g(x)).
  3. once(fn) returns a function that calls fn the first time only, and on every later call returns the first result without calling fn again.
main.js
function makeCounter() {
}

function compose(f, g) {
}

function once(fn) {
}

const next = makeCounter();
console.log(next(), next(), next());

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…