Thuta Learning
JavaScript
AdvancedProgrammingBeginner

Closures

JavaScriptLesson 2825 min

What you'll walk away with

  • Explain a closure as a function bundled with the lexical environment it was created in
  • Show with two counters that every call to outer() creates a fresh set of variables
  • Predict results knowing a closure keeps the variable (the binding), not a copy of its value
  • Write a factory function whose state cannot be changed directly from outside

Explain it simply

Explain it simply

Picture a function as a person leaving home with a backpack. When the function is created, it packs the variables that surround it into that backpack. Even after the house (the outer function) has closed up and finished running, the things in the backpack can still be used. The function together with its backpack is called a closure.

Only the function itself can open the backpack; code outside cannot reach in. That makes closures one of the most basic ways in JavaScript to keep private data that nobody else can touch.

Problem → Why → Solution

The problem: all three buttons report number 3

Say you create three click handlers for three buttons inside a loop. You expect each handler to remember its own index, yet whichever button you press, the log says "Button 3 clicked", and there is no button 3 at all. No error message appears, which makes this bug hard to track down.

buttons.js
var handlers = [];

for (var i = 0; i < 3; i++) {
  handlers.push(function () {
    console.log("Button " + i + " clicked");
  });
}

handlers[0](); // Button 3 clicked  (expected: Button 0)
handlers[1](); // Button 3 clicked  (expected: Button 1)

Why does it print 3?

The closure does not take a snapshot of i's value; it remembers the variable i itself. Declared with var, there is only one i for the whole loop, and all three handlers share it. By the time a handler runs, the loop has finished and i is 3. Changing the loop to let i gives every iteration its own fresh i, and the bug disappears.

Core concept: a function carries the environment it was born in

JavaScript uses lexical scope: which variables a function can see is decided by where the function is written in the code, not by where it is called from. When a function is created, the engine stores inside it a reference to the surrounding environment, the place where those variables live. The function plus that reference is what we call a closure.

Normally, once a function finishes, its local variables can be cleaned out of memory. But if it returns an inner function and that inner function is stored somewhere, the inner function still points at the environment, so the engine cannot throw it away. That is why count stays alive after outer() has returned.

The most important detail is that every call to outer() creates a brand-new environment. counter1 and counter2 are built from the same code, yet each one holds its own separate count. That is why counter2 starts at 1 even after counter1 has been called twice.

text
Two closures, two environments
------------------------------
counter1 ---> inner()  --refers to-->  [ env #1 ]  count = 2
counter2 ---> inner()  --refers to-->  [ env #2 ]  count = 1

outer() has returned, but env #1 and env #2 stay alive
because counter1 and counter2 still point at them.

A closure keeps the variable itself, a live binding, not a copy of its value. If the variable changes later, the closure sees the new value. This is exactly what makes private state work, and it is also the root of the loop bug. Because closures hold references, accidentally capturing a large object or a DOM node you no longer need keeps that memory from being freed.

Strictly speaking, every JavaScript function is a closure, because every function remembers the environment it was created in. You only notice the effect when an inner function escapes its outer function: when it is returned, passed along as a callback, or stored in an object property.

Mental model: a function plus its backpack
  1. Calling outer() creates a new env
  2. inner points at that env
  3. outer() returns, the env survives
  4. Each inner() call reuses the same vars

The backpack holds the real variables, never copies of their values.

General pattern

javascript
function makeThing(setting) {
  let state = initialValue;        // private to this call

  return function useThing(arg) {  // the closure
    // reads/updates state and setting
    return result;
  };
}

const thing = makeThing(value);    // new environment each call

Declare variables inside an outer function and return an inner function (or an object of methods) that uses them. The returned function becomes the only door into that private state.

Example: two counters and a bank account with a private balance

The first part calls outer() twice to show that the two counters keep separate state. In the second part, createBankAccount() hides balance inside a closure and only lets the deposit, withdraw and getBalance methods touch it. The final line shows what you get when you try to read account.balance directly.

closures.js
// Basic closure: each call to outer() creates a new count
function outer() {
  let count = 0;
  return function inner() {
    count++;
    return count;
  };
}

const counter1 = outer();
const counter2 = outer();

console.log(counter1()); // 1
console.log(counter1()); // 2
console.log(counter2()); // 1 (separate instance)

// Practical example: a private balance
function createBankAccount(initialBalance) {
  let balance = initialBalance; // only the methods below can see this

  return {
    deposit(amount) {
      balance += amount;
      return `Deposited ${amount}. Balance: ${balance}`;
    },
    withdraw(amount) {
      if (amount > balance) return "Insufficient funds";
      balance -= amount;
      return `Withdrew ${amount}. Balance: ${balance}`;
    },
    getBalance() {
      return balance;
    },
  };
}

const account = createBankAccount(1000);
console.log(account.deposit(500));
console.log(account.withdraw(300));
console.log(account.withdraw(5000));
console.log(`Balance: ${account.getBalance()}`);
console.log(account.balance); // undefined: not a property

Code breakdown

  1. Line 3let count = 0;

    This line runs again on every call to outer(), so each call gets a new count. That is each counter's own private state.

  2. Lines 4-7return function inner() {

    inner uses count, so when it is returned it takes the environment holding count with it. count++ updates the real variable, not a copy.

  3. Line 15console.log(counter2()); // 1 (separate instance)

    Although counter1 has run twice, counter2 uses the environment from the second outer() call, so it starts from 1.

  4. Line 19let balance = initialBalance; // only the methods below can see this

    balance is not a property of the returned object; it is a local variable of createBankAccount, shared by the three methods through their closures.

  5. Line 27if (amount > balance) return "Insufficient funds";

    Since only these methods can change balance, the rule "never withdraw more than you have" is enforced in one place. withdraw(5000) exits here without touching balance.

  6. Line 42console.log(account.balance); // undefined: not a property

    The object has no balance property, so this prints undefined. Even writing account.balance = 1000000 from outside would only add a new property; the private balance stays untouched.

You should see
1
2
1
Deposited 500. Balance: 1500
Withdrew 300. Balance: 1200
Insufficient funds
Balance: 1200
undefined

Live bindings: a closure sees the latest value

Because a closure holds the variable itself, changing the variable after the function is created changes what the closure reads. In makeGreeter() below, name was "Aye" when greet was created but is "Mya" by the time it runs, so it prints "Hello, Mya". In the loop example, var gives the whole loop one binding, while let gives each iteration a new one.

live-binding.js
function makeGreeter() {
  let name = "Aye";
  const greet = () => console.log(`Hello, ${name}`);
  name = "Mya"; // changed after greet was created
  return greet;
}
makeGreeter()(); // Hello, Mya

const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);

console.log("var:", withVar.map((f) => f()).join(", ")); // 3, 3, 3
console.log("let:", withLet.map((f) => f()).join(", ")); // 0, 1, 2

Closures for memoization (a cache)

One of the most practical uses of a closure is a cache of results that were already computed. memoize() hides a Map inside a closure, and when a call with the same argument comes again it returns the stored result instead of redoing the work. Code outside cannot clear or corrupt the cache, which keeps it reliable.

memoize.js
function memoize(fn) {
  const cache = new Map(); // private to this memoized function
  return function (n) {
    if (cache.has(n)) return `${cache.get(n)} (cached)`;
    const result = fn(n);
    cache.set(n, result);
    return `${result} (computed)`;
  };
}

const slowSquare = (n) => n * n;
const fastSquare = memoize(slowSquare);
console.log(fastSquare(12)); // 144 (computed)
console.log(fastSquare(12)); // 144 (cached)

In real projects

Where this shows up in real projects

You use closures every day, often without noticing. Every event listener's handler remembers surrounding variables, such as a product id, through a closure. React's useState and useEffect hooks capture each render's values in closures too, which is why "stale closures", code reading an old value, are a well-known bug category among React developers.

Libraries lean on closures heavily. Utilities such as debounce() and throttle() keep a timer id inside a closure to control how often a function actually runs. Factories that take configuration once and hand back a ready-made function, such as createLogger("payments") or createApiClient(baseUrl), are closures as well. Before class syntax existed, closures were the only way to get private data, and although #private fields exist today, function-based code still uses this pattern widely.

Common mistakes

Common mistakes

1. Creating closures inside a var loop

Callbacks created in for (var i = 0; ...) all share one i and see only its final value. Use let, or a style like forEach((item, index) => ...) where each iteration receives fresh parameters.

2. Assuming a closure snapshots the value

If you expect a handler to remember the value from creation time and then reassign the variable, the handler reads the new value. When you need the value exactly as it was, copy it into a new const first and use that inside the closure.

3. Capturing big data you do not need

If a callback needs only one id but refers to the entire response object, the whole object stays in memory for as long as the callback lives. Extract just the value you need before capturing it, and remove listeners you no longer need with removeEventListener.

Best practices

Best practices

  • Use let or const instead of var in loops that create callbacks.
  • For private state, return only the methods you want to expose and keep the variables hidden.
  • Name factories createX or makeX so it is obvious that every call produces a new instance.

Mini challenge

Mini challenge: a counter factory with a step

Write a createCounter(start, step) factory. Create two counters and print results that prove changing one never affects the other.

  • start defaults to 0 and step defaults to 1
  • Provide four methods: increment(), decrement(), reset(), value()
  • reset() puts the counter back to its start value
  • count must not be a property on the object ("count" in counter is false)
counter-factory.js
function createCounter(start = 0, step = 1) {
  // TODO: declare the private count variable

  return {
    // TODO: increment() adds step and returns the new count
    // TODO: decrement() subtracts step and returns the new count
    // TODO: reset() goes back to start and returns it
    // TODO: value() returns the current count
  };
}

// TODO: create a default counter and one that starts at 100 with step 10
// TODO: change both, then print their values, a reset, and "count" in a

Expected: The two counters must keep separate values: a = 1 b = 120 b after reset = 100 a is untouched = 1 count exposed? false

Show hint

Declare let count = start; inside createCounter and use count directly from the methods. Do not write this.count, because that would make it a public property.

Show solution
counter-factory.js
function createCounter(start = 0, step = 1) {
  let count = start;

  return {
    increment() {
      count += step;
      return count;
    },
    decrement() {
      count -= step;
      return count;
    },
    reset() {
      count = start;
      return count;
    },
    value() {
      return count;
    },
  };
}

const a = createCounter();
const b = createCounter(100, 10);

a.increment();
a.increment();
a.decrement();
b.increment();
b.increment();

console.log(`a = ${a.value()}`);
console.log(`b = ${b.value()}`);
console.log(`b after reset = ${b.reset()}`);
console.log(`a is untouched = ${a.value()}`);
console.log(`count exposed? ${"count" in a}`);

Quick quiz 1 / 3

After var handlers = []; for (var i = 0; i < 3; i++) handlers.push(() => i);, what does handlers[0]() return?

Quick quiz 2 / 3

Using outer() from the example: const c1 = outer(); const c2 = outer(); c1(); c1(); — what does c2() return?

Quick quiz 3 / 3

Which statement about a variable captured by a closure is true?

What to remember

  • A closure is a function bundled with the lexical environment it was created in.
  • Every call to the outer function makes a new environment, so each instance a factory returns has its own state.
  • A closure holds the variable, not a copy, which causes the var loop bug that let fixes.
  • Private state, caches, event handlers and factories are the main uses; avoid capturing large data you do not need.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Closures | Thuta Learning