Closures — JavaScript

A closure is a function that still remembers the variables from the scope (the part of the code) where it was made. It remembers them even after the outer…

Think of a visit counter. Every time you call it, the number goes up: 1, 2, 3. The number has to be kept between two calls. But you don't want to put it in a global variable, because any code can change a global variable. A function can keep that number by itself.

Here is how. In JavaScript, you can make a function inside another function. The inner function still remembers the outer function's variables, even after the outer function has finished running. This is how you build counters, function factories (functions that make other functions), and data that can't be changed from outside.

A function that remembers its variables

Here is that visit counter as code. Its number is kept in count:

function makeCounter() {
  let count = 0;

  return {
    inc: () => ++count,
    peek: () => count,
  };
}

const a = makeCounter();
const b = makeCounter();

a.inc();
a.inc();
console.log(a.peek()); // 2
console.log(b.peek()); // 0
console.log(a.count);  // undefined

The scope of count (the part of the code where count can be used) is the body of makeCounter. A function that still remembers the variables from the scope where it was made is called a closure. inc and peek are closures: both were made inside makeCounter, and both remember count.

In short: a function remembers the variables around the place where it was written. Every time the outer function is called, those variables are made new.

A function that returns a function

makeGreeting below is a function factory. makeGreeting takes a greeting, then returns a new function that uses that greeting:

function makeGreeting(greeting) {
  return function (name) {
    return greeting + ", " + name + "!";
  };
}

const greetMorning = makeGreeting("Good morning");
const greetEvening = makeGreeting("Good evening");

console.log(greetMorning("Budi"));       // Good morning, Budi!
console.log(greetEvening("Ani"));        // Good evening, Ani!
console.log(makeGreeting("Hi")("Rina")); // Hi, Rina!

Methods that share one variable

Several closures can use the same variable. The shopping basket below keeps its items in the array items:

function makeBasket() {
  const items = [];

  return {
    add(item) {
      items.push(item);
    },
    count() {
      return items.length;
    },
  };
}

const basket = makeBasket();
basket.add("book");
basket.add("pencil");
console.log(basket.count()); // 2
console.log(basket.items);   // undefined

⚠️ Why isn't the closure remembering the right thing?

🔬 Try it yourself

The tool below holds more closure patterns, from a private counter to the well-known loop bug. Pick one pattern, then see which variables its closure remembers.

TL;DR: A closure is a function that still remembers the variables from the scope (the part of the code) where it was made. It remembers them even after the outer function (the function it was made in) has finished running. Every call to the outer function makes new variables, so calling the counter maker makeCounter() twice gives two separate counts. Use a closure for functions that return functions (in makeGreeting("Hi")("Rina"), the second pair of brackets calls the returned function) and for data that can only change through the methods you provide.

⚡ A function that remembers its variables

Write:

function makeCounter() {
  let count = 0;

  return {
    inc: () => ++count,
    peek: () => count,
  };
}

const a = makeCounter();
const b = makeCounter();

a.inc();
a.inc();
console.log(a.peek()); // 2
console.log(b.peek()); // ?
Guess first: inc adds one to count, and peek reads it. inc is called twice through a. What does b.peek() give?

0. Every call to makeCounter() makes a new count, so a and b each have their own count.

Meaning: makeCounter() has finished running, but inc and peek can still use count. A function that still remembers the variables from its outer scope (the part of the code where it was made) is called a closure.

⚡ No changing it from outside

Write:

console.log(a.count); // undefined

Meaning: count is a variable inside makeCounter, not a property of the object a. So from outside, you can only use count through inc and peek. If count were stored as a property of the object, any code could overwrite it.

⚡ A function that returns a function

Write:

function makeGreeting(greeting) {
  return function (name) {
    return greeting + ", " + name + "!";
  };
}

const greetMorning = makeGreeting("Good morning");
console.log(greetMorning("Budi")); // Good morning, Budi!

Meaning: makeGreeting returns a function, not text. The returned function remembers the greeting from the makeGreeting call that made it. So you can call greetMorning at any time, and it always uses Good morning.

What you will learn