⚡ JavaScript: Fix a WeakMap Key Surviving Longer Than Expected
A WeakMap only allows its entry to be garbage collected once there are zero remaining strong references to the key object anywhere in the program, because the WeakMap’s own reference to that key is deliberately weak and never counts toward keeping it alive. Holding the key object alive through any other strong reference, a closure capturing it, an array it was pushed into for logging, a cached DOM node reference, keeps the WeakMap entry alive right along with it, even though the code that actually cares about the caching behavior has long since finished using the key and expected the entry to have been reclaimed.
🔎 The Problem
const cache = new WeakMap();
const debugLog = []; // accidental strong reference
function processNode(node) {
cache.set(node, computeExpensiveResult(node));
debugLog.push(node); // keeps every node alive forever,
// so its WeakMap entry never gets
// collected even after the node is
// removed from the DOM and should
// be eligible for GC
return cache.get(node);
}
✅ Fix: Hunt Down the Stray Strong Reference
- Audit every array, object, or closure in the same module that might be holding onto the exact object used as a WeakMap key, since a single stray strong reference anywhere defeats the whole point of using a WeakMap for that cache.
- Use the browser DevTools memory snapshot’s retainer path on a sampled object to confirm what’s actually keeping it alive, rather than assuming the WeakMap itself is the leak just because its entries aren’t shrinking.
- If debug logging genuinely needs to reference the same objects, store a WeakRef to them instead of a direct strong reference, so the logging array itself doesn’t become the thing preventing collection.
🚨 Why This Is Dangerous
- A cache intentionally built on WeakMap specifically to avoid memory growth can still grow unbounded in production, and because the WeakMap itself behaves correctly, the actual leak hides in whatever unrelated code is holding the key alive instead.
A WeakMap’s weak reference only matters if it’s the only reference — one stray strong one anywhere else in the program and you’ve built a regular Map with extra steps.




