WeakMap reachability
suggest changeJavaScript garbage collectors determine whether objects are reachable; the language does not require a reference-counting algorithm or define when collection occurs.
A WeakMap holds its keys weakly. If a key is no longer reachable elsewhere, the key and its associated value can be collected. This makes a weak map useful for attaching metadata whose lifetime should not exceed the lifetime of an object:
const metadata = new WeakMap();
let button = document.querySelector("button");
metadata.set(button, { clickCount: 0 });
metadata.get(button).clickCount += 1;
button = null;
// The document still references the element while it is in the page.
// After it is removed, and nothing else references it, it and its metadata
// are eligible for garbage collection. The collection time is unspecified.
Weak-map keys must be objects or non-registered symbols. A WeakMap is not iterable and does not expose its size, because observable enumeration would reveal garbage-collection behavior. Weak references do not guarantee prompt cleanup and should not be used for essential resource management; close files, connections, and similar resources explicitly.