Skip to content
FrontDepth, Home

JavaScript Deep Dive

Closures

How a function keeps access to the variables of the scope it was created in — from counters and callbacks to the scope chain, memory retention and stale closures in React.

JuniorMiddleSeniorUpdated 13 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

What a closure is

A is a function together with access to the variables of the scope it was created in. In JavaScript every function is a closure: when a function is created, it remembers the around it, and it keeps that access even after the outer function has returned.

JavaScript
function makeGreeting(greeting) {
  return function (name) {
    return greeting + ", " + name + "!";
  };
}

const hello = makeGreeting("Hello");
const salam = makeGreeting("Salam");

console.log(hello("Ada")); // "Hello, Ada!"
console.log(salam("Ada")); // "Salam, Ada!"

makeGreeting has already finished when hello("Ada") runs, yet the inner function still reads greeting. Each call to makeGreeting created its own greeting, so hello and salam don't interfere with each other.

Lexical scope

JavaScript uses : what a function can see is decided by where it is written in the code, not by where it is called from.

JavaScript
const message = "global";

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

function run() {
  const message = "local";
  printMessage();
}

run(); // "global"

printMessage was written at the top level, so it looks up message there. The message inside run is invisible to it, even though run is the caller.

Key points

  • A closure is not special syntax. It is simply what happens when a function uses a variable from an outer scope.
  • An inner function can read and change outer variables.
  • Inner scopes see outer ones; outer scopes cannot see into inner ones.
JuniorExample

Closures in everyday code

You use closures every day, often without noticing. The most common cases:

Private state. A factory function returns functions that share a variable nobody else can reach.

JavaScript
function createCounter() {
  let count = 0;
  return {
    increment() {
      count += 1;
      return count;
    },
    getValue() {
      return count;
    },
  };
}

const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.getValue()); // 2
console.log(counter.count); // undefined

count is not a property of the object — it lives in the scope of createCounter. The only way to change it is through increment. Call createCounter() again and you get a completely independent counter.

Event handlers. A handler remembers the data it was set up with:

JavaScript
function setupLikeButton(button, postId) {
  let likes = 0;
  button.addEventListener("click", () => {
    likes += 1;
    button.textContent = "Likes: " + likes;
    console.log("Liked post " + postId);
  });
}

Every button set up this way gets its own likes and its own postId.

Callbacks. Functions passed to filter, map, setTimeout or then read variables from the surrounding code:

JavaScript
function filterByMinPrice(products, minPrice) {
  return products.filter((product) => product.price >= minPrice);
}

The arrow function is a and, at the same time, a closure over minPrice.

React components. Every inline handler in a component is a closure over the props and state of the render that created it:

TSX
import { useState } from "react";

function LikeButton() {
  const [likes, setLikes] = useState(0);
  return <button onClick={() => setLikes(likes + 1)}>Likes: {likes}</button>;
}

This works because each render creates a new handler that sees the current likes. The senior part of this topic shows what happens when an old handler survives longer than its render.

MiddleWeb platform

How closures work: environments and the scope chain

The ECMAScript spec describes closures with Environment Records; articles and older editions of the spec call this structure a . An environment holds the bindings (variables) of one scope plus a reference to its outer environment.

Three rules explain almost everything:

  1. Every call creates a new environment. Calling a function creates a fresh environment for its parameters and local variables. Blocks that contain let, const or class declarations get their own environment too.
  2. A function remembers where it was created. When a function object is created, the engine stores the current environment in a hidden internal slot of that object (the spec names the slot Environment). When the function is called later, the outer reference of its new environment points to that stored environment — not to the caller's.
  3. Lookup walks the chain. To resolve a name, the engine checks the current environment, then the outer one, and so on up to the global environment. Reading a name that is not declared anywhere throws a ReferenceError.

This chain of environments is the scope chain. A closure is simply a function whose stored environment keeps the chain alive after the outer function has returned.

Bindings, not values

A closure captures variables, not snapshots of their values. Closures created during the same call share one environment:

JavaScript
function makeBox() {
  let value = 0;
  const get = () => value;
  const set = (next) => {
    value = next;
  };
  return { get, set };
}

const a = makeBox();
const b = makeBox();
a.set(5);
console.log(a.get(), b.get()); // 5 0

a.get and a.set share one environment; b has its own because it came from a separate call.

Hoisting and the TDZ

Lookup happens when the function runs, not when it is created, so a closure can refer to a variable declared further down:

JavaScript
const read = () => late;
const late = "ready";
console.log(read()); // "ready"

Calling read() before the const late line would throw a ReferenceError: thanks to the binding already exists, but it is still in the .

MiddlePitfalls

Pitfalls: var in loops and shared bindings

The classic interview bug:

JavaScript
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// 3, 3, 3

var is function-scoped (or global), so the whole loop has one i. All three callbacks close over that same binding. The runs the timer callbacks only after the current script has finished — by then the loop is over and i is 3.

With let the output is 0, 1, 2:

JavaScript
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
// 0, 1, 2

For a let declaration in the head of a for loop, the spec creates a new binding for every iteration and copies the current value into it before the increment runs. Each callback captures a different i. for...of and for...in loops with let or const also get a fresh binding per iteration. (A classic for (const i = 0; i < 3; i++) throws a TypeError on the first i++, because a const cannot be reassigned.)

Before ES2015, the fix was an that created a new scope for each iteration:

JavaScript
for (var i = 0; i < 3; i++) {
  (function (j) {
    setTimeout(() => console.log(j), 0);
  })(i);
}

Passing i as an argument copies its current value into a new parameter j.

Other traps

  • Expecting a snapshot. A closure reads a variable's value at the moment it runs. If the variable changes between creating the closure and calling it, you get the new value. To freeze a value, pass it as an argument or copy it into a const in a new scope.
  • Shared vs. separate state. Functions returned from one call share their environment; functions from different calls do not. Mixing these up leads to "why did this counter change?" bugs.
  • Regular functions don't capture this. A regular function gets its this from how it is called, so inside setTimeout(function () { ... }) the this is not your object. Arrow functions have no this of their own and use the this of the enclosing scope, just like a closed-over variable.
MiddleExample

Useful patterns: once, memoize, debounce, modules

Many small utilities are built on closures. Most of them are : they take a function and return a new one that keeps private state in a closure.

once — run a function at most one time:

JavaScript
function once(fn) {
  let called = false;
  let result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

The returned function is a regular function, so this and the arguments are forwarded unchanged.

memoize — with a cache that lives in the closure:

JavaScript
function memoize(fn) {
  const cache = new Map();
  return (arg) => {
    if (!cache.has(arg)) {
      cache.set(arg, fn(arg));
    }
    return cache.get(arg);
  };
}

Note that this cache never shrinks — the senior section on memory comes back to it.

debounce — a helper keeps the pending timer id between calls, so each new call can cancel the previous one:

JavaScript
function debounce(fn, delay) {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...args), delay);
  };
}

works the same way, but stores the time of the last run (or a "cooling down" flag) instead of a timer id.

Module pattern — before ES modules, an IIFE was the standard way to hide implementation details:

JavaScript
const counterModule = (function () {
  let count = 0;
  return {
    increment() {
      count += 1;
      return count;
    },
    reset() {
      count = 0;
    },
  };
})();

count cannot be reached from outside; only increment and reset can touch it. Today every ES module file has its own scope, so the IIFE is rarely needed, but the idea — expose functions, keep state in a closure — is still how factory functions and many library APIs are built.

SeniorWeb platform

Memory, garbage collection and performance

A closure keeps its environment reachable, and only frees what is unreachable. So a variable lives as long as some function that can still access it is alive — whether or not that function will ever run again.

Typical leak sources

Most closure-related come from a closure held by something long-lived:

  • Event listeners. A listener on window, document or a global store keeps its closure, and everything it references, alive until removed.
  • Timers. A setInterval callback and everything it captures stay alive until clearInterval.
  • Caches in closures. The memoize above never forgets. Add a size limit, or use a WeakMap for object keys so entries can be collected with their keys.
  • Detached DOM nodes. A closure that references a removed element keeps it and its subtree in memory.

Tie a listener's lifetime to the feature that created it. An AbortController removes every listener registered with its signal in one call:

JavaScript
function trackClicks(button) {
  const clicks = [];
  const controller = new AbortController();

  button.addEventListener("click", (event) => clicks.push(event.timeStamp), {
    signal: controller.signal,
  });

  return () => controller.abort();
}

What exactly is retained

In the spec model, a closure keeps its whole environment chain. Engines optimize this and typically keep only the variables that inner functions actually reference — but with limits. In V8 (Chrome, Node.js), the variables captured by any inner function are typically stored in one shared context object per scope, and every closure created in that scope points to it:

JavaScript
function setup() {
  const bigData = new Array(1_000_000).fill(0);
  const id = 42;

  function logSize() {
    console.log(bigData.length);
  }
  logSize();

  return () => id;
}

const getId = setup();

getId only uses id, but logSize captured bigData, so both live in the same context and bigData can stay in memory as long as getId does. This is an engine detail, not spec behavior, and it can change between versions. If a large object is needed only briefly, don't capture it in a long-lived scope, or declare it with let and set it to null when you are done.

To find a leak, take heap snapshots in the Memory panel of Chrome DevTools and inspect the Retainers of the object that should be gone.

Performance

Creating a closure allocates a function object (plus a context if it captures variables) — cheap, and rarely relevant outside very hot code. In React the real cost is usually the new identity a function gets on each render, which can defeat memo or re-trigger effects.

SeniorFramework

React hooks and stale closures

Every render of a component is a function call. It creates new props, new state constants and new functions, and every effect, handler and callback created during that render closes over that render's values — this is why react.dev describes state as a snapshot. Trouble starts when a function from an old render keeps running: that is a .

TSX
import { useEffect, useState } from "react";

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <p>{count}</p>;
}

The effect runs once, so the interval callback belongs to the first render, where count is 0. Every tick calls setCount(0 + 1): the counter shows 1 and stays there.

Fixes, from simplest

  1. Functional update. If you only need the previous state, don't read it from the closure: setCount((c) => c + 1). React passes in the latest value, the effect keeps [], and the interval is created once.
  2. Correct dependencies. Adding count to the dependency array re-runs the effect with a fresh closure. It is correct, but here it tears down and recreates the interval on every change. Don't silence react-hooks/exhaustive-deps: a missing dependency is usually a stale closure waiting to happen. The same goes for useCallback and useMemo — useCallback(fn, []) freezes the first render's values.
  3. Refs. A ref is a mutable box shared by all renders, so a long-lived callback that reads ref.current always gets the latest value. Update the ref in an effect or event handler, not during rendering.
  4. useEffectEvent (stable since React 19.2) — for logic inside an effect that must see the latest props or state but should not make the effect re-synchronize:
TSX
import { useEffect, useEffectEvent, useState } from "react";

function Ticker({ step }: { step: number }) {
  const [count, setCount] = useState(0);

  const onTick = useEffectEvent(() => {
    setCount((c) => c + step);
  });

  useEffect(() => {
    const id = setInterval(() => onTick(), 1000);
    return () => clearInterval(id);
  }, []);

  return <p>{count}</p>;
}

onTick always sees the current step, and changing step does not restart the interval. Effect Events are left out of the dependency array, may only be called from inside effects, and must not be passed to other components or hooks. Don't use them to hide dependencies that really should re-run the effect.

SeniorInterview tips

Interview tips

A 30-second definition. "A closure is a function plus the variables of the scope where it was created. JavaScript resolves variables lexically, so the function keeps access to them even after the outer function has returned." Then sketch a counter factory: it shows you can apply the idea, not just recite it.

Questions you are likely to get

  • What does this loop log? The var/let + setTimeout puzzle. Explain why: one shared binding vs. a new binding per iteration.
  • Implement once, memoize or debounce. Say where the state lives (in the closure) and handle the details: forwarding this and arguments, clearing the previous timer.
  • How do you make data private? Closures (factory function or module pattern); for classes, mention #private fields as the modern alternative.
  • Can closures cause memory leaks? Yes — they keep their environment reachable. Name concrete sources: forgotten listeners, intervals that are never cleared, unbounded caches.
  • Why does my effect see an old value? Each render has its own closures. Fixes: dependencies, functional updates, refs, useEffectEvent.

Mistakes that cost points

  • Saying closures "copy" variables. They capture bindings, so changes made after creation are visible.
  • Saying a closure exists only when a function is returned. Every function closes over its scope; returning it or passing it somewhere just makes the effect visible.
  • Mixing up scope and this. Closures capture variables; this in a regular function depends on the call.
  • Calling closures slow or leaky by nature. They cost an allocation and retain what they reference while they are reachable — no more than that.

Senior signal

Connect the theory to practice: how you would find a leak (heap snapshot, Retainers view), why a stable function identity matters for memo and effect dependencies, and when you would choose a functional update, a ref or useEffectEvent.

JuniorReview checklist

What to check when reviewing closures

Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. Skip it and you ship callbacks that read old values, or listeners and caches that hold memory long after the feature is gone.

  • Does a callback that outlives its render read state or props directly? An interval callback, an effect with [] or useCallback(fn, []) keeps the values of the render that created it: a . Expect a functional update like setCount((c) => c + 1), correct dependencies or a ref, not a silenced react-hooks/exhaustive-deps.
  • Is every listener on window, document or a global store removed, and every setInterval cleared? Until then, cannot free the closure or anything it references. Find the matching removeEventListener, clearInterval or controller.abort().
  • Does a loop that creates callbacks use var? With for (var i = 0; i < 3; i++), three timer callbacks share one i and log 3, 3, 3. Expect let in the loop head, or const in for...of.
  • Does the code expect the value from the moment the closure was created? A closure captures the variable, not a snapshot, and reads it when it runs. To freeze a value, pass it as an argument or copy it into a const.
  • Does a regular function callback use this? Inside setTimeout(function () { ... }), this is not your object: closures capture variables, not this. Expect an arrow function, or fn.apply(this, args) in wrappers such as once.
  • Does a cache inside a closure only grow? A memoize built on a Map never forgets. Ask for a size limit, or a WeakMap when the keys are objects.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.

Guided tours through the source of real libraries that rely on it.