ILILCode
HomeJavaScriptAdvanced

Closures: functions that remember

A function keeps access to the scope where it was created — that is the whole idea, and it is powerful.

Lesson 13 of 23 in JavaScript11 min2 exercises

Every time a function runs, it gets a fresh scope. A closure is a function that keeps a reference to that scope after the outer function has returned. The variables stay alive because something still points at them.

A counter factory
function makeCounter() {
  let count = 0;

  return function () {
    count += 1;
    return count;
  };
}

const next = makeCounter();
next(); // 1
next(); // 2

const other = makeCounter();
other(); // 1 — its own count, not shared

That count is private. Nothing outside makeCounter can read or set it — only the returned function can. This is how you build state without classes or globals.

Three everyday uses

  • Private state — the counter above, or a cache nobody else can touch.
  • Factories — const double = multiplyBy(2) produces a specialised function.
  • Run once / memoise — wrap a function so it only does the expensive work the first time.
Only once
function once(fn) {
  let done = false;
  let value;

  return function (...args) {
    if (!done) {
      value = fn(...args);
      done = true;
    }
    return value;
  };
}

Try it

Two counters, two states

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Build a counter factory

Write makeCounter() that returns a function. Each call of that returned function returns 1, then 2, then 3, and so on. Two counters created from two calls must not share state.

exercise.js
console · run your code or check the answer
02

Exercise

Run a function only once

Write once(fn) that returns a new function. The first call runs fn and returns its result. Every later call returns that same first result without running fn again.

exercise.js
console · run your code or check the answer