WeakMap and WeakSet
WeakMap and WeakSet allow garbage collection of objects when there are no other strong references to those objects. WeakMap keys must be objects or non-registered symbols. Weak collections are not enumerable because their contents can disappear as garbage collection occurs.
They are useful for metadata associated with object lifetimes, private associations, and certain caching strategies.
WeakMap Metadata
const metadata = new WeakMap();
let element = {};
metadata.set(element, { createdAt: Date.now() });
console.log(metadata.get(element));
element = null;
// The original object can now become collectible.💡 WeakMap does not create a strong reference from the collection to its object key, so once the key is otherwise unreachable, the key and associated entry can eventually be collected.
Key Takeaways
- WeakMap keys do not keep their objects alive by themselves.
- Weak collections are intentionally not enumerable.
- WeakMap is useful for object-associated metadata.
Knowledge Check
Why can WeakMap help avoid retaining an object?