Closures and the Garbage Collector in JavaScript
Closures prevent GC from freeing variables. Here is how the GC interacts with closures and what to do about it.
Closures and the Garbage Collector in JavaScript
The garbage collector (GC) in JavaScript uses mark-and-sweep: it marks all reachable objects and frees the rest. Closures affect reachability by keeping references to their lexical environment.
Normal GC Behavior (Without Closures)
function foo() { const big = new Array(1_000_000); // ... use big ... } foo(); // big is no longer reachable; the GC can free it `` After `foo` returns, `big` has no references. The GC frees it. ### Closures Change Reachability ```js function foo() { const big = new Array(1_000_000); return () => big.length; // closure keeps big alive } const getLen = foo(); // big is still reachable (through getLen's lexical environment) // the GC cannot free it `` `getLen` holds a reference to `foo`'s lexical environment, which contains `big`. As long as `getLen` is reachable, `big` is reachable. The GC keeps it. ### When the GC Can Free Closed-Over Variables ```js function foo() { const big = new Array(1_000_000); const len = big.length; return () => len; // closure only references len, not big } const getLen = foo(); // modern engines may free big (only len is captured) `` If the closure only references `len`, some engines can free `big` because it is not reachable through the closure. But this is an optimization, not guaranteed. ### Ensuring Variables Are Freed ```js function foo() { const big = new Array(1_000_000); const len = big.length; big = null; // drop the reference (if declared with let) return () => len; } `` Explicitly nulling the reference helps, but `const` cannot be reassigned. Use `let` if you need to null it. ### WeakMap for Weak References ```js const cache = new WeakMap(); function process(obj) { if (cache.has(obj)) return cache.get(obj); const result = compute(obj); cache.set(obj, result); return result; } // when obj is GC'd, the entry is automatically removed `` `WeakMap` keys are weakly held. When the key is GC'd, the entry is removed. This prevents leaks in caches. ### WeakRef (ES2021) ```js let obj = { data: "important" }; const ref = new WeakRef(obj); // later: const target = ref.deref(); if (target) { console.log(target.data); // obj is still alive } else { console.log("obj was garbage collected"); } `` `WeakRef` lets you hold a weak reference to an object. The GC can free the object even if the `WeakRef` exists. ### The Takeaway Closures keep their lexical environment reachable, preventing the GC from freeing closed-over variables. To help the GC: extract only what you need, null references when done, use `WeakMap` for caches, and use `WeakRef` for optional references. Some engines optimize away unused closed-over variables, but do not rely on it.
Closures hold a reference to their lexical environment, keeping all closed-over variables reachable. As long as the closure is reachable, the GC cannot free those variables. This is useful for data privacy but can cause memory growth.
Extract only what you need (close over len, not the whole array), null references when done (use let instead of const), use WeakMap for caches (keys are weakly held), and use WeakRef for optional references.
WeakMap keys are weakly held. When a key is garbage collected, the entry is automatically removed. This prevents memory leaks in caches where closures might otherwise keep keys alive forever.
Some modern engines optimize this: if a closure does not reference a variable, the engine may free it even though it is in the same lexical environment. But this is an optimization, not guaranteed across all engines.
WeakRef (ES2021) holds a weak reference to an object. The GC can free the object even if the WeakRef exists. Use it when a closure needs optional access to an object that should not prevent GC.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

