JavaScript › Memory Management & Garbage Collection

How do closures unintentionally keep large objects alive longer than expected?

Intermediate

Answer

A closure retains access to its entire enclosing scope, not just the specific variables it uses — so if a large object is declared in the same scope as a function that's kept alive (e.g. returned or stored), that object can stay reachable via the closure even if the returned function never actually uses it.
function outer() {
  const largeArray = new Array(1000000).fill('data');
  const smallValue = 42;
  return function inner() {
    return smallValue; // doesn't use largeArray, but engines may still retain the whole scope
  };
}
Real-world example Investigating unexpectedly high memory usage traced back to a closure retaining an entire unused scope.

Common follow-ups: How would you restructure the code to avoid retaining largeArray unnecessarily?