WeakMap and WeakSet are specialized collections in JavaScript similar to Map and Set,
but they hold “weak” references to their keys (in WeakMap) or values (in WeakSet),
meaning those objects can be garbage collected if no other references exist.
1️⃣ WeakMap
A WeakMap is a collection of key-value pairs where:
- Keys must be objects
- Values can be anything
- Keys are weakly referenced, so if the key object is deleted elsewhere, it’s automatically removed from the WeakMap.
Example:
const weakMap = new WeakMap();
let user = { name: "Teekam" };
weakMap.set(user, "Active");
console.log(weakMap.get(user)); // "Active"
user = null; // remove strong reference
// The { name: "Teekam" } object is now garbage-collected
✅ The entry is automatically deleted when user becomes unreachable — preventing memory leaks.
Key Points About WeakMap:
- Keys must be objects, not primitives.
- It’s not iterable (no
.forEach()or.size). - Great for storing private data tied to objects.
Example (Private Data):
const privateData = new WeakMap();
class User {
constructor(name) {
privateData.set(this, { name });
}
getName() {
return privateData.get(this).name;
}
}
const user1 = new User("Teekam");
console.log(user1.getName()); // "Teekam"
2️⃣ WeakSet
A WeakSet is like a Set, but it only stores objects, and they’re weakly referenced.
Example:
const weakSet = new WeakSet();
let obj = { id: 1 };
weakSet.add(obj);
console.log(weakSet.has(obj)); // true
obj = null; // object becomes unreachable -> garbage collected
✅ Automatically removed when no references remain.
Key Points About WeakSet:
- Stores only objects.
- Not iterable (no
.forEach(),.size, etc.). - Useful for tracking objects without preventing garbage collection.
3️⃣ WeakMap vs WeakSet
| Feature | WeakMap | WeakSet |
|---|---|---|
| Stores | Key-value pairs | Only objects (values) |
| Key Type | Must be object | Must be object |
| Garbage Collection | Removes entries when key object is gone | Removes object when unreachable |
| Iterable | ❌ No | ❌ No |
| Use Case | Private data storage | Track object existence |
💡 In Short:
- WeakMap: Stores key-value pairs where keys are weakly referenced objects.
- WeakSet: Stores weakly referenced objects only.
Both help prevent memory leaks by allowing automatic cleanup when objects are no longer in use.