⚡ JavaScript: Fix a WeakMap Entry Disappearing Before You Expected
A WeakMap holds its keys weakly, meaning an entry can be garbage collected — and silently vanish from the map — as soon as nothing else in the program holds a strong reference to that key object. Code that assumes “the DOM node is still on the page, so the WeakMap entry must still be there” can be wrong, because DOM presence and garbage-collection eligibility aren’t the same thing, and the timing of collection is never guaranteed or synchronous.
🔎 The Problem
function trackElement(el) {
const metadata = { seen: Date.now() };
weakMetadataMap.set(el, metadata);
// 'el' passed in here may have no other strong reference anywhere
// once this function returns, the entry can be collected at any later time
}
✅ Fix: Keep an Explicit Strong Reference Where It Matters
- Keep an explicit strong reference to any key you need to guarantee survives for the WeakMap entry to remain retrievable — for a DOM node, that usually means the node itself still being attached to the document, not just a variable that once pointed to it.
- If deterministic lifetime control is required rather than “maybe collected, maybe not, at an unspecified time,” use a regular Map with your own explicit cleanup logic instead of a WeakMap, since a WeakMap’s entire purpose is to NOT give that guarantee.
- Don’t rely on
WeakMap.has()returning false as a signal that something specific happened in your business logic — treat it only as “this key is no longer reachable,” which can be true for reasons unrelated to your intended logic.
🚨 Why This Is Dangerous
- Because garbage collection timing isn’t specified or deterministic, a bug caused by this can appear intermittently in production under memory pressure and never reproduce consistently in a quick local test.
A WeakMap doesn’t promise your entry will disappear the instant its key becomes unreachable, or that it won’t — it only promises that nothing about the WeakMap itself will keep that key alive.

