Learn the concept
Data Structures
WeakMap and WeakSet hold weak references to object keys/values, allowing garbage collection when no other references exist. Unlike Map and Set, they are not iterable and have no size property.
WeakMap and WeakSet are specialized collections that hold weak references to objects. A weak reference does not prevent the garbage collector from reclaiming the object — if the only remaining reference to an object is through a WeakMap key or WeakSet entry, the object can be garbage collected.
| Feature | Map | WeakMap |
|---------|-----|---------|
| Key types | Any value (string, number, object) | Objects only (no primitives) |
| Garbage collection | Keys prevent GC (strong reference) | Keys do NOT prevent GC (weak reference) |
| Iterable | Yes (for...of, .forEach()) | No |
| .size property | Yes | No |
| .clear() method | Yes | No |
| Methods | get, set, has, delete, entries, keys, values | get, set, has, delete only |
Primitive values (strings, numbers) are compared by value and can be recreated anywhere. The engine cannot track when "all references" to the number 42 are gone — the concept doesn't apply. Objects are compared by reference, so the engine knows exactly when no code can reach a specific object anymore.
const metadata = new WeakMap();
function trackElement(el) {
metadata.set(el, { clickCount: 0, created: Date.now() });
}
// When el is removed from DOM and dereferenced, metadata is cleaned upconst privateData = new WeakMap();
class User {
constructor(name, password) {
privateData.set(this, { password });
this.name = name;
}
checkPassword(input) {
return privateData.get(this).password === input;
}
}WeakSet stores objects (not values) and is mainly used to tag objects without preventing garbage collection:
WeakMap/WeakSet exist to solve memory leaks. Regular Map/Set keep strong references — if you store an object as a Map key and forget to delete it, the object can never be garbage collected even if no other code uses it. WeakMap/WeakSet solve this by allowing the garbage collector to reclaim objects when they are no longer reachable through any strong reference.
const clickCounts = new WeakMap();
document.querySelectorAll('button').forEach((btn) => {
clickCounts.set(btn, 0);
btn.addEventListener('click', () => {
const count = clickCounts.get(btn) + 1;
clickCounts.set(btn, count);
console.log(`Button clicked ${count} times`);
});
});
// If a button is removed from the DOM and dereferenced,
// its click count is automatically garbage collected.
// With a regular Map, you'd need to manually delete the entry.Track scroll positions, click counts, or validation state for DOM elements without preventing garbage collection when elements are removed.
React and Vue use WeakMap internally to associate component state with fiber/VNode objects without creating memory leaks during component unmounting.
Build a memoize function that caches results keyed by object arguments using WeakMap, ensuring cached entries are automatically cleaned up.