Topic: Learning notes

JavaScript Closures: How Functions Remember Outer Variables

Use counters to explore closures and lexical scope, shared and independent state, and memory cleanup.

What happens to a function’s local data if a function created inside it still needs that data after the outer call finishes?

That question was my starting point for learning JavaScript closures. The key is to separate two things: when a function call finishes, its execution context leaves the call stack. But if a reachable function can still use bindings from the lexical environment where it was created, those bindings can remain available.

The function has finished, but can its data still be found? · Source: GIPHY

Start with a counter

function createCounter(initial = 0) {
  let count = initial;

  return function increment() {
    count += 1;
    return count;
  };
}

const first = createCounter();

console.log(first()); // 1
console.log(first()); // 2

const second = createCounter();

console.log(second()); // 1

The first call to createCounter() creates a new execution context and its own count. After it returns the increment function, the createCounter execution context leaves the call stack.

The returned increment can still access the count in the environment where it was defined. The first call to first() changes that count from 0 to 1; the second uses the same binding and changes it to 2. A function together with its access to its surrounding lexical environment is a closure.

Each call to first() also creates a new execution context for that invocation of increment. What remains available between calls is the outer count binding, not the execution context from the previous call to first().

Calling createCounter() again creates another outer environment, so second has its own count, starting at 0. The two functions have the same code but use independent counter bindings.

Where does a function look for a variable?

JavaScript uses lexical scope: a function’s access to outer variables depends on where it was defined. Calling it from another function does not make the caller’s local variables its outer scope.

const label = "outer";

function showLabel() {
  return label;
}

function run() {
  const label = "inner";
  return showLabel();
}

console.log(run()); // "outer"

showLabel is defined in the outer scope, so it finds the outer label. The variable with the same name inside run is local to run; it is not part of the outer environment where showLabel was defined.

When resolving a name, JavaScript starts with the innermost visible scope and works outward. An inner variable with the same name hides the outer one, a behavior known as variable shadowing.

The course uses a “backpack” as a way to picture the connection between a function and its surrounding data. The image helps explain why the data can still be found, but the backpack is not necessarily a snapshot of values. A closure accesses bindings, so if an outer binding changes, the function can read the updated value later.

In the modern ECMAScript specification, the [[Environment]] internal slot of an ordinary JavaScript function object records the lexical environment in which it was created. It is not a property that ordinary JavaScript code can access directly.

Closures can share state or keep it separate

The two counters above came from separate calls to createCounter(), so they have different count bindings. Functions created during the same outer call can also share one outer variable:

function createAccount() {
  let balance = 0;

  return {
    deposit(amount) {
      balance += amount;
    },
    getBalance() {
      return balance;
    },
  };
}

const account = createAccount();
account.deposit(5);

console.log(account.getBalance()); // 5

Both deposit and getBalance can access the balance created by that call. Another call to createAccount() would create a different balance. This lets us keep state alongside the methods that operate on it and expose access through those methods.

To determine whether state is shared, look at what the functions reference as well as how often the outer function is called. Different closures can still use the same outer object or other shared data.

Closures are not limited to returned functions

Returning a function is one way to demonstrate a closure. An asynchronous callback can retain access to outer variables too:

function remind(name) {
  setTimeout(() => {
    console.log(`Hi, ${name}`);
  }, 0);
}

remind("Mia"); // logs "Hi, Mia" later

Even after remind has finished, the timer callback can still read name. The callback is passed to setTimeout rather than returned from remind, and the runtime calls it later. A delay of 0 does not mean it runs before the current synchronous code finishes.

Keep the data available for the function that runs later. · Source: GIPHY

Remembering whether an action has run

Closures are useful for keeping state between calls. For example, this once wrapper runs the supplied action at most once:

function once(action) {
  let called = false;

  return function (...args) {
    if (called) return;

    called = true;
    return action(...args);
  };
}

const greetOnce = once((name) => `Hi, ${name}`);

console.log(greetOnce("Mia")); // "Hi, Mia"
console.log(greetOnce("Mia")); // undefined

called remains in the outer environment, allowing the same greetOnce function to remember whether the action has run. Another common use is memoization: storing inputs and results so a result can be reused when the same input appears again. A real cache also needs a way to compare inputs and a decision about when to clear entries.

Closures and garbage collection

A closure keeps needed data accessible. That is what makes it useful, but keeping an unneeded function, event listener, or cache reachable for too long can also retain related data longer than expected.

Using createCounter from the first example:

let counter = createCounter();
const alias = counter;

counter = null;

console.log(alias()); // 1

Even though counter is now null, alias still points to the original function, so it can call the function and access count. The associated data can become eligible for collection once it is no longer reachable through any relevant reference. The runtime decides when garbage collection actually happens; assigning null does not guarantee immediate cleanup.

Closures connect a function with the environment where it was defined. Together with function execution contexts and callbacks and higher-order functions, this makes it easier to follow how data is used across calls.

References