Skip to content
Home Interview JavaScript Closures — Silent Memory Leak from DOM Nodes

JavaScript Closures — Silent Memory Leak from DOM Nodes

Where developers are forged. · Structured learning · Free forever.
📍 Part of: JavaScript Interview → Topic 2 of 5
RSS memory grew for 6h until OOMKill — closures captured jsdom DOM nodes.
🔥 Advanced — solid Interview foundation required
In this tutorial, you'll learn
RSS memory grew for 6h until OOMKill — closures captured jsdom DOM nodes.
  • A closure is a function plus its [[Environment]] slot — the live lexical bindings from where it was defined.
  • Closures capture variables by reference, never by value. This is the root of the 'loop bug'.
  • In V8, all inner functions from the same scope share a context record; one large variable can keep the entire scope alive.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer
  • Closures bundle a function with its lexical environment — the variables in scope when the function was defined, not invoked
  • The [[Environment]] internal slot on every function points to the scope chain at definition time
  • The loop bug: var creates one binding per loop, so all callbacks share the same i — use let for per-iteration bindings
  • Memory cost: closures keep the entire context alive — one large variable in a shared scope prevents GC of everything else
  • Production insight: stale closures in React hooks cause silent state bugs — fix with functional updates or useRef
🚨 START HERE

Quick Debug: Closure Memory Leaks & Stale Values

These are the two most critical closure problems in production. Here's how to diagnose and fix them fast.
🟡

DOM event handler closure keeps parent scope alive — memory not released after element removal

Immediate ActionRun `performance.memory.usedJSHeapSize` in browser console. If it keeps growing after removing DOM elements, you've got a closure leak.
Commands
heap snapshot (DevTools Memory tab) — filter by '(closure)' and look for retained objects with unexpected large arrays.
`getEventListeners(window)` in console (Chrome-only) to list all event listeners. Check for any that shouldn't exist.
Fix NowReplace anonymous closure listeners with named functions, then remove them explicitly in cleanup. Or use `{ once: true }` if the event should fire only once.
🟡

Stale closure in React useEffect — interval runs but uses old state

Immediate ActionCheck the dependency array of useEffect. If you're using `[]` but referencing state, the closure captured the initial value.
Commands
Add a `console.log(state)` inside the effect — if it logs the same value every time, that's the captured stale value.
Use functional update for setState: `setCount(c => c + 1)` instead of `setCount(count + 1)`.
Fix NowChange `[ ]` to `[state]` or use `useRef` to hold a mutable reference that doesn't require the effect to re-run.
Production Incident

A Silent Memory Leak: Closures Holding DOM Nodes

A Node.js microservice serving real-time dashboards started OOM-killing every 12 hours. The culprit: an event listener closure retained a reference to a large data object that should have been garbage-collected after each request.
SymptomRSS memory grew linearly over time — no plateau. After 6 hours, memory exceeded container limit and Kubernetes OOMKilled the pod. Heap snapshots showed thousands of detached DOM nodes (in a server-side app? Actually, the team used jsdom for server-side rendering and the closures kept the window objects alive).
AssumptionThe team assumed that once the request handler returned, all local variables would be GC'd. They didn't account for the event listener attached to a jsdom window object that still referenced the large dataset via closure.
Root causeThe event listener was added with window.addEventListener('resize', handler), where handler was a closure that captured the entire data variable from the outer scope. The listener was never removed, so the window object and all its DOM tree stayed reachable even after the response was sent. The closure's [[Environment]] kept data alive, and data kept references to the DOM.
FixRemove the event listener after the response is sent using window.removeEventListener. Alternatively, use { once: true } for one-shot events, or structure the code so the closure doesn't capture large variables directly (pass only necessary data). In the incident, they switched to using a WeakMap to associate data with the window object and cleaned up in a finally block.
Key Lesson
Every DOM event listener that captures data in a closure must be explicitly removed when no longer needed.Use once: true for single-use event handlers to avoid the removal overhead.Prefer passing minimal data into callbacks rather than capturing large objects from the outer scope.Memory profiles are your friend — heap snapshots showing many detached DOM trees point directly at closure retention.
Production Debug Guide

Symptom → Action grid for the three most common closure failures

All setTimeout/setInterval callbacks log the same final valueYou have the classic loop bug. Change var to let in the loop header, or wrap the callback in an IIFE that captures the current iteration value.
React component shows stale state — count never updates in setIntervalStale closure inside useEffect. Use the functional update form of setState: setCount(prev => prev + 1), or refactor with useRef to hold the latest value and reference that in the closure.
Memory grows monotonically in a long-running Node serverUse Chrome DevTools heap snapshot (or Node's --inspect). Look for closures under (closure) in the tree. Check for event listeners that are never removed or large arrays captured in closure scope that shouldn't be.

Closures are the single most interrogated concept in JavaScript interviews — and for good reason. They're not just a language quirk; they're the engine behind module patterns, memoization, event handlers, React hooks, and virtually every callback-heavy system you'll write in production. If you don't own closures cold, you'll struggle to reason about async bugs, memory leaks, and stateful logic at scale.

The problem closures solve is deceptively simple: how does a function retain access to variables that were defined in a scope that has already finished executing? In most mental models of code, once a function returns, its local variables evaporate. Closures break that assumption in the most useful way possible — they keep a live reference to the surrounding lexical environment, not a snapshot, not a copy.

By the end of this article you'll be able to explain the V8-level mechanics of how closures are stored, identify the three classic closure interview traps (the loop bug, the memory leak, and the stale reference), write module patterns and memoization from scratch, and answer the follow-up questions that trip up even experienced devs. Let's build this from the engine up.

How the JavaScript Engine Actually Creates a Closure

When the JS engine parses a function, it records the function's lexical environment — the scope chain that was active at the point of definition, not the point of invocation. This is baked into the function object itself as an internal [[Environment]] slot. You can't read it directly, but it's always there.

When the outer function returns, its Execution Context is popped off the call stack. Normally the local variables would be garbage-collected. But if any inner function holds a reference to those variables through its [[Environment]] slot, the garbage collector sees them as still reachable — so it keeps them alive in a structure called a closure record (or context object in V8 terms).

This is why closures aren't 'magic' — they're a predictable consequence of lexical scoping plus garbage collection. The engine asks one question: 'Is anyone still pointing at this variable?' If yes, it stays alive.

Critically, the closure captures variables by reference, not by value. If the outer variable mutates after the closure is created, the closure sees the new value. This is the root cause of the infamous loop-closure bug and every stale-value head-scratcher you'll encounter in production.

io/thecodeforge/js/closure_internals.js · JAVASCRIPT
12345678910111213141516171819202122232425262728
/**
 * @package io.thecodeforge
 * Demonstration of shared variable reference in closures
 */

function createCounterPair() {
  let count = 0; // Lives in the heap-allocated closure record

  function increment() {
    count += 1; // Mutating the shared reference
    return count;
  }

  function decrement() {
    count -= 1;
    return count;
  }

  return { increment, decrement };
}

const counter = createCounterPair();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1 (sees the mutated state)

const independent = createCounterPair();
console.log(independent.increment()); // 1 (isolated scope)
▶ Output
1
2
1
1
🔥Interview Gold:
When asked 'what is a closure?', most candidates say 'a function inside a function'. The correct answer is: 'A closure is a function bundled together with its lexical environment — specifically the set of variable bindings that were in scope when the function was defined.' Mention the [[Environment]] internal slot and watch the interviewer's eyebrows rise.
📊 Production Insight
In V8, closures are heap-allocated context objects, not stack frames.
The GC keeps the entire context alive if any inner function references any part of it.
Rule: to minimize memory, avoid capturing large arrays in closures used in hot paths.
🎯 Key Takeaway
Closures capture variable bindings by reference, not value.
Every function has an internal [[Environment]] slot that points to its lexical scope chain.
The GC determines closure lifetime — closures keep variables alive as long as they're reachable.

The Classic Loop-Closure Bug — and Three Ways to Fix It

This is the most-asked closure question in JavaScript interviews, bar none. It seems simple, and that's exactly what makes it dangerous. The bug happens because var is function-scoped. Every iteration of the loop doesn't create a new variable — it mutates the same memory location. By the time the callbacks fire, the loop has completed and the variable holds its final value.

There are three idiomatic fixes: using let (block-scoped), using an IIFE to create a new scope per iteration, or using .forEach. Understanding why let works is key: the ES6 spec mandates that a let variable in a for loop header is re-bound for every iteration of the loop.

io/thecodeforge/js/loop_solutions.js · JAVASCRIPT
123456789101112131415161718192021
/**
 * @package io.thecodeforge
 * Senior-level loop closure solutions
 */

// Solution 1: Block Scoping (Modern Standard)
for (let i = 0; i < 3; i++) {
    setTimeout(() => console.log('let:', i), 100);
}

// Solution 2: IIFE (Immediate Invoked Function Expression)
for (var i = 0; i < 3; i++) {
    (function(capturedIndex) {
        setTimeout(() => console.log('iife:', capturedIndex), 100);
    })(i);
}

// Solution 3: Argument Binding via .bind()
for (var i = 0; i < 3; i++) {
    setTimeout(console.log.bind(console, 'bind:', i), 100);
}
▶ Output
let: 0
let: 1
let: 2
iife: 0
iife: 1
iife: 2
bind: 0
bind: 1
bind: 2
⚠ Watch Out:
The let fix works because the ECMAScript spec mandates that let in a for loop header creates a new binding for each iteration — it's not just block-scoping the variable, it's actively re-binding it. If you use let in a while loop without manually reassigning, you don't get this guarantee.
📊 Production Insight
Production bugs from the loop closure often appear in async flows: array of Promises, event listeners in loops, or batch API calls.
The fix with let is zero-overhead — the spec creates new bindings per iteration with negligible memory cost.
Rule: always use let in for loops that create callbacks, not var.
🎯 Key Takeaway
var is function-scoped — one binding per function, not per loop iteration.
let in a for loop creates a new binding each iteration — this fixes the closure bug.
The three fixes: let, IIFE, or bind — choose let for clarity.

Closures in Production — Module Pattern, Memoization & Memory Pitfalls

Closures allow for powerful patterns like the Module Pattern (private state) and Memoization (caching). However, they come with a memory cost. Because a closure keeps its entire [[Environment]] alive, a large object captured in a closure will never be garbage-collected as long as the closure exists.

In V8, if multiple inner functions are defined in the same scope, they share a single context object. This means if one inner function captures a large array, that array stays in memory even for other functions that don't use it, provided they were created in the same environment.

io/thecodeforge/js/memoization.js · JAVASCRIPT
123456789101112131415161718192021222324
/**
 * @package io.thecodeforge
 * Production-grade Memoization via Closures
 */

const memoize = (fn) => {
    const cache = new Map();
    return (...args) => {
        const key = JSON.stringify(args);
        if (cache.has(key)) return cache.get(key);
        
        const result = fn(...args);
        cache.set(key, result);
        return result;
    };
};

const expensiveOperation = memoize((num) => {
    console.log("Computing...");
    return num * 2;
});

console.log(expensiveOperation(10)); // Computing...
console.log(expensiveOperation(10)); // (Cached)
▶ Output
Computing...
20
20
💡Pro Tip:
In V8, if a closure doesn't actually reference a variable from the outer scope, the engine is smart enough not to retain it — this is called 'closure elision'. But the moment any inner function in a shared scope references a variable, V8 must keep the entire context alive.
📊 Production Insight
A common production pitfall: creating closures inside a hot loop that capture large arrays. Each closure keeps its own context, leading to memory bloat.
Profile with heap snapshots: look for (context) entries that contain arrays bigger than expected.
Rule: in performance-critical paths, pass data as arguments instead of capturing it in a closure.
🎯 Key Takeaway
Modules and memoization rely on closures for private state.
One large captured variable keeps the entire shared context alive.
Closure elision helps, but only if no inner function references the variable.

Stale Closures in React Hooks — The Modern Production Gotcha

Stale closures occur when a function 'remembers' a variable from an old render cycle. In React, because useEffect and useCallback create closures, if the dependency array is incorrect, the closure holds onto old state values.

To fix stale closures, developers use functional updates in setState or the useRef pattern, which provides a stable reference that always points to the latest value without requiring the closure to be re-created.

io/thecodeforge/js/react_fix.js · JAVASCRIPT
123456789101112131415
/**
 * @package io.thecodeforge
 * Fixing stale closures in React hooks
 */

// Functional Update Fix
const [count, setCount] = useState(0);

useEffect(() => {
    const id = setInterval(() => {
        // Bypasses the closure by using the state updater callback
        setCount(prev => prev + 1);
    }, 1000);
    return () => clearInterval(id);
}, []); // Safe now
▶ Output
// Count increments correctly regardless of initial closure
⚠ Watch Out:
The React team's ESLint plugin eslint-plugin-react-hooks enforces exhaustive dependency arrays precisely to catch stale closures at lint time. Disabling that rule with // eslint-disable-next-line is almost always the wrong call.
📊 Production Insight
React's exhaustive-deps lint rule catches 95% of stale closures at compile time.
When you see 'React Hook useEffect has a missing dependency', don't suppress it — fix the dependency array or use functional updates.
Rule: the safest pattern for intervals/timeouts is setCount(prev => prev + 1) — no closure dependency needed.
🎯 Key Takeaway
Stale closures in hooks capture values from an old render cycle.
Functional updates in setState circumvent the closure by using a callback.
useRef provides a stable container that always points to the current value.

Closures in Event Handlers — The Hidden Memory Leak Pattern

Event listeners attached to DOM nodes (or Node.js EventEmitter objects) create closures that capture the surrounding scope. If the listener is never removed, the entire captured scope stays in memory — including the DOM node itself, preventing it from being garbage-collected when it's removed from the document.

This is the single most common closure-related memory leak in browser apps. The fix is simple: always pair every addEventListener with a corresponding removeEventListener in the cleanup phase. For React, use the cleanup function returned from useEffect. For plain JS, use addEventListener's { once: true } option for one-shot events.

io/thecodeforge/js/event_listener_cleanup.js · JAVASCRIPT
12345678910111213141516171819202122232425262728
/**
 * @package io.thecodeforge
 * Safe event listener pattern with closure cleanup
 */

// Bad: listener never removed, leaks scope
function addBadHandler(button, data) {
  button.addEventListener('click', function handleClick() {
    console.log(data); // captures `data` forever
  });
  // button removed later but handleClick still references data
}

// Good: remove listener explicitly
function addGoodHandler(button, data) {
  function handleClick() {
    console.log(data);
  }
  button.addEventListener('click', handleClick);
  
  // Later, when button is removed:
  // button.removeEventListener('click', handleClick);
  // Or in a React useEffect cleanup:
  // return () => button.removeEventListener('click', handleClick);
}

// Best for one-shot: use { once: true }
button.addEventListener('click', () => console.log(data), { once: true });
▶ Output
// No output example — pattern demonstration
🔥Interview Question:
Senior interviewers love asking: 'How do closures cause memory leaks in the browser?' The answer: an unremoved event listener that captures a large object in its closure keeps that object (and the whole scope chain) alive, even if the DOM node is removed. The fix is always to call removeEventListener in the cleanup.
📊 Production Insight
In a Single Page App, navigating between routes often replaces DOM nodes. If event listeners are not cleaned up, each navigation leaks memory.
Chrome DevTools heap snapshot filter by 'Detached DOM Tree' will show these leaked nodes.
Rule: always pair addEventListener with removeEventListener in your component lifecycle.
🎯 Key Takeaway
Every addEventListener must have a matching removeEventListener.
Use { once: true } for events that fire once.
Detached DOM trees in heap snapshots often point to uncleaned closure-capturing listeners.
🗂 Closure Scoping: var vs let in Loops
Why one creates a classic bug and the other doesn't
Aspectvar in a for looplet in a for loop
ScopeFunction-scoped (one binding for the whole loop)Block-scoped (new binding per iteration)
Closure behaviourAll callbacks share the same variable referenceEach callback captures its own independent binding
Loop bug riskHigh — classic closure trapNone — spec guarantees per-iteration binding
When to useAlmost never in modern codeDefault choice for all loop variables
Fix required?Yes — IIFE, .forEach, or switch to letNo — works correctly out of the box
Memory overheadOne variable slot allocatedNew binding per iteration (negligible)

🎯 Key Takeaways

  • A closure is a function plus its [[Environment]] slot — the live lexical bindings from where it was defined.
  • Closures capture variables by reference, never by value. This is the root of the 'loop bug'.
  • In V8, all inner functions from the same scope share a context record; one large variable can keep the entire scope alive.
  • Stale closures in React are solved using functional updates or useRef to maintain a stable pointer to current state.
  • Every event listener that uses a closure must be explicitly removed to prevent memory leaks.

⚠ Common Mistakes to Avoid

    Thinking closures capture VALUES
    Symptom

    You expect a closure to remember the value of a variable at the time of creation, but it actually sees the latest value when executed.

    Fix

    Remember: closures capture variable BINDINGS (references), not values. If the variable is updated, the closure sees the update. Use an IIFE or let per iteration to capture a specific value.

    Creating memory leaks with unremoved event listeners
    Symptom

    Memory grows over time, especially in SPAs after navigating pages. Heap snapshots show detached DOM trees.

    Fix

    Always remove event listeners with removeEventListener in component cleanup. Use { once: true } for one-shot events. In React, use the useEffect cleanup function.

    Suppressing React's exhaustive-deps lint rule
    Symptom

    State in useEffect or useCallback appears stale — it always logs the initial value, not the current one.

    Fix

    Never suppress the lint rule. Either add the missing dependency or use functional state updates (setCount(prev => prev + 1)) to avoid capturing the state value.

Interview Questions on This Topic

  • QExplain the 'Diamond of Death' equivalent in JS Closures: if two functions share a parent scope, can they access each other's private variables? Why/Why not?SeniorReveal
    No, they cannot directly access each other's private variables. Each function only has access to its own local scope and the shared parent scope. They share the same closure record (the parent's context object), but they cannot access each other's local variables because those are in separate function scopes. However, because they share the same context object, modifying a property on that object would affect the other function's view if that property is a shared reference (like an object or array). This is the diamond-like pattern: two children sharing a parent scope but not each other's private data.
  • QWhy does 'use strict' change the behavior of closures in certain contexts (like global scope variable leaking)?Mid-levelReveal
    In sloppy mode, the this inside a regular function is the global object (or undefined in strict mode). This doesn't directly change closure mechanics, but it affects how implicit global variables are created. In sloppy mode, if you assign to an undeclared variable, it becomes a property on the global object — but that's not a closure issue. A more relevant effect: in strict mode, the arguments object in a closure behaves differently (no caller or callee properties). Also, strict mode eliminates with statements that could confuse lexical scoping. The interviewer likely wants to test whether you understand that closures themselves work identically in strict and sloppy mode — the difference is in this binding and variable resolution for undeclared variables.
  • QDescribe the performance implications of creating closures inside a high-frequency loop (e.g., a game loop or a 60fps animation).SeniorReveal
    Each closure creation allocates a new context object on the heap. In a tight loop running at 60fps, creating closures each frame will generate significant GC pressure, potentially causing jank. The context object itself is small, but the repeated allocation and collection will trigger minor GC cycles. Solution: pre-define your callback functions outside the loop and reuse them, or use a factory pattern that only creates closures once. Also, avoid capturing large objects in those closures — they'll prevent the GC from efficiently collecting the context. Use requestAnimationFrame with a reusable handler that takes its needed state from a shared mutable object rather than capturing new closures each frame.
  • QHow does the V8 engine optimize closures to prevent memory bloating? (Discuss context object sharing).SeniorReveal
    V8 uses a technique called 'context object sharing' (or 'closure optimization'). When multiple inner functions are created in the same outer function, they share a single context object that contains all the variables from the outer scope. This reduces memory overhead compared to creating a separate context object for each inner function. However, there's a catch: if any one of those inner functions references a variable from the outer scope, that variable (and all variables in the shared context) remain alive as long as any of the inner functions exist. This can lead to unexpected retention: a function that doesn't use a large array still keeps it alive because it shares the context with a sibling that does. V8 also applies 'context elision' — if an inner function doesn't reference any outer variables, it doesn't get a context object at all. But as soon as one variable is referenced, the entire context is created.

Frequently Asked Questions

Does every JavaScript function create a closure?

Theoretically, yes. Every function holds a reference to its outer lexical environment via the internal [[Environment]] slot. However, engines like V8 optimize this by 'eliding' closures if no outer variables are actually used inside the function.

Can I manually 'destroy' a closure to free memory?

You cannot destroy the closure itself, but you can nullify the references it holds. If a closure points to a large object data, setting data = null in the outer scope (or ensuring the closure no longer references it) allows the garbage collector to reclaim that specific memory.

How do closures work with asynchronous code (Promises/Async-Await)?

They work identically. Since closures capture the lexical environment, an async callback will still have access to the variables defined in its parent scope even if the parent function finished executing minutes ago.

What is the difference between a closure and a pure function?

A pure function has no side effects and its output depends only on inputs — it does not rely on or modify external state. A closure by definition captures external state from its lexical environment, making it impure unless that captured state is immutable and not mutated. So closures are generally not pure functions, though you could write a closure that captures only constants.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousTop 50 JavaScript Interview QNext →React Interview Questions
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged