Chapter 16 of 49

JavaScript Closures

Normally, when a function finishes running, its local variables are gone. Call it again and everything starts fresh.

But in the Callbacks & Higher-Order Functions chapter we saw something strange:

function createMultiplier(factor) {
    return function (number) {
        return number * factor;
    };
}

const double = createMultiplier(2);

console.log(double(5));

Output:

10

By the time we call double(5), createMultiplier() has already finished. So where does factor (which is 2) come from?

The answer is a closure. Closures are one of the most asked-about JavaScript concepts in interviews, and once you understand Scope (and the scope chain), they're not difficult at all.

What is a Closure?

A closure is a function together with the variables from the scope where it was created. The function keeps access to those variables even after the outer function has finished running.

In simple words: a function remembers the place where it was born.

Think of a student leaving school with a backpack. Even after leaving the classroom, the student still carries the books they packed there. An inner function leaves its outer function carrying a "backpack" of the variables it needs.


Quick Recap: Lexical Scope

In the Scope chapter, we learned that an inner function can read variables from its outer scopes:

function outer() {
    const message = "Hello from outer";

    function inner() {
        console.log(message); // found in outer's scope
    }

    inner();
}

outer();

Output:

Hello from outer

JavaScript uses lexical scope: what a function can access is decided by where the function is written in the code, not by where it is called from. "Lexical" just means "based on the written source code".

A closure is what happens when that inner function is used outside of its outer function.


Your First Closure

Let's return the inner function instead of calling it immediately:

function outer() {
    const message = "Hello from outer";

    function inner() {
        console.log(message);
    }

    return inner; // return the function itself, not inner()
}

const myFunction = outer(); // outer() runs and finishes here

myFunction(); // ...but message is still available

Output:

Hello from outer

Step by step:

1. outer() is called → a new scope is created with message = "Hello from outer"
2. inner is created inside that scope → it keeps a link to that scope
3. outer() returns inner and finishes
4. Normally message would be thrown away, but inner still links to it,
   so JavaScript keeps it alive
5. myFunction() runs inner → looks up message through its saved link → found!

That saved link from a function to the scope where it was created is the closure.

Technically, every function in JavaScript forms a closure over its surrounding scope. We usually only call it "a closure" when it matters, which is when the function outlives the scope it was created in.


The Classic Example: A Counter

function createCounter() {
    let count = 0;

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

const counter = createCounter();

console.log(counter());
console.log(counter());
console.log(counter());

Output:

1
2
3

The value of count survives between calls, because the returned function keeps count alive. And nobody outside can change count directly:

console.log(count); // ❌ ReferenceError: count is not defined

The only way to touch count is through the function we returned.

Each Call Creates a Separate Closure

Every time createCounter() runs, a brand new scope with a brand new count is created:

function createCounter() {
    let count = 0;

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

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

console.log(counterA());
console.log(counterA());
console.log(counterB());
console.log(counterA());

Output:

1
2
1
3
counterA ──► its own scope { count: 3 }
counterB ──► its own scope { count: 1 }

The two counters never interfere with each other.


Closures Remember Variables, Not Values

A closure doesn't take a snapshot of the values at the moment it's created. It keeps a live link to the variables themselves. If a variable changes, the closure sees the new value.

function setup() {
    let greeting = "Hello";

    const sayIt = () => console.log(greeting);

    greeting = "Namaste"; // changed AFTER sayIt was created

    return sayIt;
}

const sayIt = setup();
sayIt();

Output:

Namaste

This detail explains the famous loop problem below.


Closures for Private Data

JavaScript developers have used closures for a long time to hide data. Here's a simple bank account where the balance can only be changed through the functions we choose to expose:

function createAccount(owner, openingBalance) {
    let balance = openingBalance; // private

    function deposit(amount) {
        if (amount <= 0) {
            console.log("Deposit must be positive");
            return;
        }
        balance += amount;
        console.log(owner + " deposited ₹" + amount);
    }

    function withdraw(amount) {
        if (amount > balance) {
            console.log("Insufficient balance");
            return;
        }
        balance -= amount;
        console.log(owner + " withdrew ₹" + amount);
    }

    function getBalance() {
        return balance;
    }

    // return an object holding the three functions
    return { deposit, withdraw, getBalance };
}

const account = createAccount("Aman", 1000);

account.deposit(500);
account.withdraw(2000);
account.withdraw(300);
console.log("Balance: ₹" + account.getBalance());

console.log(account.balance); // there is no such property

Output:

Aman deposited ₹500
Insufficient balance
Aman withdrew ₹300
Balance: ₹1200
undefined

All three functions close over the same balance and owner variables. Code outside can't set balance to a million rupees; it can only go through deposit() and withdraw(), which check the rules.

({ deposit, withdraw, getBalance } is shorthand for { deposit: deposit, withdraw: withdraw, getBalance: getBalance }. We'll study objects in detail in the Objects chapter.)

This idea of keeping data private and exposing only some functions is called encapsulation. Later, you'll see that classes offer another way to do this with private fields.


Function Factories

createMultiplier() from the beginning of this chapter is a function factory: it uses closures to produce customised functions.

function createGreeter(greeting) {
    return name => greeting + ", " + name + "!";
}

const greetEnglish = createGreeter("Hello");
const greetHindi = createGreeter("Namaste");

console.log(greetEnglish("Priya"));
console.log(greetHindi("Priya"));

Output:

Hello, Priya!
Namaste, Priya!

Each greeter remembers its own greeting.


The Famous Loop Problem

This is probably the most common closure question in interviews:

for (var i = 1; i <= 3; i++) {
    setTimeout(function () {
        console.log(i);
    }, 100);
}

Output:

4
4
4

Most people expect 1 2 3. Here's what really happens:

1. var is function-scoped, so there is only ONE variable i for the whole loop
2. The loop runs quickly and schedules three callbacks
   (all three close over the same i)
3. The loop ends when i becomes 4 (because 4 <= 3 is false)
4. About 100 ms later, the callbacks run and each reads i → 4, 4, 4

Fix 1: Use let

for (let i = 1; i <= 3; i++) {
    setTimeout(function () {
        console.log(i);
    }, 100);
}

Output:

1
2
3

let is block-scoped, and a for loop with let creates a new i for each iteration. Each callback closes over its own copy.

Fix 2: Create a New Scope with a Function (the Old Way)

Before let existed (it arrived in ES6, 2015), developers created a new scope for each iteration using a function that runs immediately, called an IIFE (Immediately Invoked Function Expression):

for (var i = 1; i <= 3; i++) {
    (function (j) {
        setTimeout(function () {
            console.log(j);
        }, 100);
    })(i);
}

Output:

1
2
3

Each call of the IIFE gets its own parameter j, holding the value of i at that moment. Today, just use let, but you should recognise this pattern in older code.


More Practical Uses

Run Something Only Once

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

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

const initApp = once(() => {
    console.log("App initialised");
    return "ready";
});

console.log(initApp());
console.log(initApp());

Output:

App initialised
ready
ready

The returned function remembers hasRun and result, so the setup code runs only on the first call. (...args just collects and passes on any arguments; the Spread & Rest Operators chapter explains this syntax.)

Caching Results (Memoization)

If a function is slow and always gives the same output for the same input, we can remember previous answers in a closure:

function memoize(fn) {
    const cache = {};

    return function (n) {
        if (n in cache) { // "in" checks whether cache already has the key n
            console.log("From cache: " + n);
            return cache[n];
        }
        const result = fn(n);
        cache[n] = result;
        return result;
    };
}

const slowSquare = n => {
    console.log("Calculating " + n + " * " + n);
    return n * n;
};

const fastSquare = memoize(slowSquare);

console.log(fastSquare(9));
console.log(fastSquare(9));

Output:

Calculating 9 * 9
81
From cache: 9
81

The cache object lives on inside the closure between calls, but no outside code can mess with it. Memoization is the same idea used in dynamic programming in DSA.

Closures Are Everywhere

You've likely already used closures without noticing. Any callback that uses a variable from outside itself, like a setTimeout() callback, an event handler, or an array method callback, relies on a closure.


Closures and Memory

Because a closure keeps its outer variables alive, those variables can't be freed by the garbage collector while the closure is still reachable.

Usually this is exactly what we want. But be careful not to accidentally keep large data alive:

function createReport() {
    const hugeData = new Array(1000000).fill("row"); // big!
    const rowCount = hugeData.length;

    // ✅ only uses rowCount, so a smart engine doesn't need to keep hugeData
    return () => "Rows: " + rowCount;
}

If the returned function used hugeData directly, the whole array would stay in memory as long as the function exists. Keep closures small and only capture what you need. If you no longer need a closure (for example, a long-lived event handler), remove the reference to it so its memory can be freed.


Common Mistakes

  • Expecting a snapshot. A closure sees the current value of the variable, not the value at the moment it was created.

  • Using var in loops with callbacks. All callbacks share one variable. Use let.

  • Thinking each call shares state. Each call of the outer function creates a new set of variables, so createCounter() twice gives two independent counters.

  • Returning inner() instead of inner. return inner() returns the result of calling it, not the function.


Interview Tips

A good, short answer to "What is a closure?":

"A closure is a function bundled with references to the variables of the scope it was created in. Because of lexical scoping, an inner function can access its outer function's variables even after the outer function has returned. Closures are used for data privacy, function factories, memoization, and callbacks that need to remember state."

Then give the counter example. Interviewers also love:

  • The var loop with setTimeout() (prints 4 4 4) and its two fixes.

  • Writing once(), memoize(), or a counter with increment(), decrement() and reset().

  • "Are closures bad for memory?" They keep referenced variables alive; that's only a problem if you hold on to closures (and big data) you no longer need.

Practice: write createCounter(start, step) that returns an object with next() and reset(), and a function createLimiter(limit) whose returned function returns true only for the first limit calls.

Conclusion

A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished running.

  • Closures exist because JavaScript uses lexical scope.

  • Every call of the outer function creates a fresh set of variables.

  • Closures hold live references to variables, not copies of values.

  • They're used for private data, function factories, once/memoize helpers, and almost every callback.

  • The var-in-a-loop bug is a closure problem; let fixes it.

Closures, together with scope and hoisting, explain how JavaScript functions really work. You'll keep seeing them in arrays, events, and asynchronous code.