Skip to content
YouTurkey Tech
All JavaScript topics

Closures

Intermediate

How a function keeps using the variables around it after the outer function has returned, and why a var loop prints 3, 3, 3.Builds on Scope Chain

Call stack

Empty

Scopes

Empty

Heap

Empty

Console

Empty

0/21Press Play, or step through with the arrows, to begin.
Step 0 of 21

Explanation

2 min read

On this page

What is a closure in JavaScript?

A is a function together with the environment it was created in. Every function in JavaScript keeps a link to the scope where it was written, so it can still read and change those variables later, even after the outer function has returned.

Closures are how JavaScript gives you private state, factories like makeCounter, once and debounce helpers, and callbacks that remember where they came from.

How does a closure keep its variables?

  • A function call normally throws its environment away when it returns.
  • If a function created inside that call is still reachable (returned, stored, or handed to a timer), the environment is kept alive, because that function still points to it.
  • The closure holds the variable, not a snapshot of its value. If the variable changes, the closure sees the new value.
  • Each call creates a new environment. Two calls to makeCounter() give two independent count variables.

What mistakes do people make with closures?

Mini example

function createWallet(start) {  let balance = start;  return {    deposit(amount) {      balance += amount;    },    getBalance() {      return balance;    },  };} const wallet = createWallet(100);wallet.deposit(50);console.log(wallet.getBalance()); // 150console.log(wallet.balance); // undefined: only the closures can reach it

Quick check

What does for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } print?

Further reading

All steps as text
  1. Step 1:

    The global context starts in its creation phase and sets up every declaration before any line runs.

  2. Step 2:

    makeCounter is stored as a function, counter is reserved but uninitialized, and var i starts as undefined.

    Lines 1–13

  3. Step 3:

    makeCounter() is called. Its environment links to global, and count is reserved in it.

    Line 9

  4. Step 4:

    count is initialized to 0.

    Line 2

  5. Step 5:

    The arrow function is created inside makeCounter, so it keeps a link to makeCounter's environment.

    Lines 3–6

  6. Step 6:

    makeCounter returns and leaves the stack, but its environment stays: the arrow function still needs count. That is a closure.

    Line 9

  7. Step 7:

    counter() runs the arrow function. Its environment links to makeCounter's, where it was created.

    Line 10

  8. Step 8:

    count++ looks up count: not in its own environment, so one hop out. The real variable becomes 1.

    Line 4

  9. Step 9:

    It returns 1, and console.log prints it.

    Lines 5–10

  10. Step 10:

    The second call finds the same count, still 1 from last time, and makes it 2.

    Lines 4–11

  11. Step 11:

    2 is printed. count is private: only the arrow function can reach it.

    Lines 5–11

  12. Step 12:

    Now the classic interview loop. var i is one single variable in the global environment, shared by every iteration.

    Line 13

  13. Step 13:

    setTimeout stores the callback for later; it does not run now. The callback remembers the variable i, not its current value 0.

    Line 14

  14. Step 14:

    i becomes 1 and a second callback is stored. It links to the same global environment.

    Lines 13–14

  15. Step 15:

    i becomes 2 and a third callback is stored.

    Lines 13–14

  16. Step 16:

    i++ makes i 3, so i < 3 is false and the loop ends. No callback has run yet.

    Line 13

  17. Step 17:

    The script is done and its context leaves the stack. The global environment stays, and the timers are about to fire.

  18. Step 18:

    The first callback runs. i is not in its own environment, so the lookup goes out to global and finds 3.

    Line 14

  19. Step 19:

    It prints 3, not 0.

    Line 14

  20. Step 20:

    The other two callbacks follow the same path to the same i, so each prints 3 too.

    Line 14

  21. Step 21:

    Output: 1, 2, 3, 3, 3. A closure keeps the variable, not its value; with let i, each iteration gets its own i and the loop prints 0, 1, 2.