Skip to the content

Lesson 53 of 296

Closures

What you will learn

  • What a closure is, in plain words
  • How closures work, step by step
  • Private variables with closures
  • A counter factory and a once() function
  • Where closures are used in real code
  • Closure pitfalls
On this page

What is a closure?

A closure is a function together with the variables from the place where it was created. The function remembers those variables and can keep using them, even after the outer function has finished running.

Every function in JavaScript is a closure. It only becomes noticeable when a function is used outside the place where it was created.

Step by step

function makeGreeting(greeting) {
  return function (name) {
    return `${greeting}, ${name}!`;
  };
}

const sayHello = makeGreeting("Hello");
const sayHi = makeGreeting("Hi");

sayHello("Sam");      "Hello, Sam!"
sayHi("Ali");         "Hi, Ali!"
  1. makeGreeting("Hello") runs. It has a variable greeting = "Hello".
  2. It creates an inner function and returns it. Then makeGreeting finishes.
  3. Normally greeting would be thrown away. But the inner function still uses it, so JavaScript keeps it alive.
  4. sayHello is that inner function plus its remembered greeting = "Hello".
  5. makeGreeting("Hi") runs again, with a separate greeting = "Hi". sayHi remembers that one.

Counter factory

This is the most common closure example in interviews.

function createCounter() {
  let count = 0;

  return {
    increment() {
      count++;
      return count;
    },
    decrement() {
      count--;
      return count;
    },
    getValue() {
      return count;
    }
  };
}

const counterA = createCounter();
const counterB = createCounter();

counterA.increment();      1
counterA.increment();      2
counterB.increment();      1    (its own separate count)
counterA.getValue();       2
console.log(count);        ReferenceError: count is not defined

Key points:

  • count is private. Nothing outside can read or change it except through the three methods.
  • Each call to createCounter() creates a new, separate count.
  • The closure keeps a live link to the variable, not a copy of its value. That is why increments are remembered.

once(): a function that runs only one time

function once(fn) {
  let called = false;
  let result;

  return function (...args) {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

const initialise = once(() => {
  console.log("Setting up");
  return "ready";
});

initialise();      logs "Setting up", returns "ready"
initialise();      returns "ready" with no log

Useful for payments, setup code, or anything that must never run twice. (...args collects all arguments: Lesson 62.)

Where closures are used

UseExample
Private dataThe counter above; the "module pattern"
Function factoriesmakeGreeting, makeMultiplier(2)
Callbacks and event handlersA click handler remembers variables from where it was set up
TimerssetTimeout callbacks remember variables
MemoizationA cache kept in a closure (Part 6)
Debounce and throttleTimer IDs kept in a closure (Part 6)
React hooksEvery handler and effect in a component is a closure over that render's props and state
let message = "Hello";
const show = () => console.log(message);
message = "Changed";
show();            "Changed"

The function reads the current value when it runs.

Pitfall: stale closures

In React, a function can capture a value from an old render, and keep using that old value. This is called a stale closure (Part 12). The cause is the same idea: each render creates new variables, and an old function still points to the old ones.

Pitfall: memory

Variables used by a closure stay in memory as long as the closure exists. Event listeners that are never removed can keep large objects alive. Remove listeners and clear timers when they are no longer needed.

Common mistakes

  • Thinking the inner function gets a copy of the value at creation time.
  • Expecting two counters to share the same count.
  • Forgetting the closure keeps variables in memory.

How to say it in an interview

"A closure is a function bundled with the lexical scope it was created in, so it can access those variables even after the outer function has returned. Each call to the outer function creates a fresh scope, so each returned function has its own private state, like a counter factory. Closures keep a live reference to variables, not a copy. They are used for data privacy, function factories, callbacks, memoization, debounce, and every React hook."

Key words

WordMeaning
ClosureA function plus the variables from where it was created
Lexical environmentThe variables available where a function is written
Private variableA variable that outside code cannot reach directly
Factory functionA function that creates and returns new objects or functions
Stale closureA function still using old values from an earlier run

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.