WeakMap and WeakSet
A WeakMap is a Map whose keys must be objects and are held weakly: if nothing else in the program refers to a key object, the garbage collector may remove it, and its entry disappears from the WeakMap automatically. A WeakSet is the same idea for a Set. They exist for one purpose: attaching extra information to objects without keeping those objects alive longer than they would otherwise live. This lesson is optional on a first pass; come back when you need caches or private data per object.
In One Minute
WeakMapkeys andWeakSetvalues must be objects (or non-registered symbols), never primitives.- Holding an object as a key doesn't prevent it from being garbage collected.
- They have no
size, no iteration and noclear: onlyget/set/has/delete(WeakMap) andadd/has/delete(WeakSet). - Typical uses: data or caches attached to objects you don't own, private data per object, marking objects as "seen" or "processed".
Why Weak References
A normal Map holds a strong reference to its keys. As long as the Map exists, every key object stays in memory, even if the rest of the program has forgotten about it:
const cache = new Map();
function process(student) {
cache.set(student, expensiveSummary(student));
}
// Every student ever processed stays in memory forever,
// because the cache refers to it, even after the app removes the student.With a WeakMap, the cache refers to its keys weakly. When the app drops its last reference to a student, the student can be collected, and the cache entry goes with it. No cleanup code is needed.
Map | WeakMap | |
|---|---|---|
| Key types | Anything | Objects (and non-registered symbols) |
| Keeps keys alive | Yes | No |
size, iteration, clear | Yes | No |
| Methods | get, set, has, delete and more | get, set, has, delete |
Using a WeakMap
const notes = new WeakMap();
const navika = { name: "Navika" };
const advitha = { name: "Advitha" };
notes.set(navika, "Pays by check");
notes.set(advitha, "Sibling discount");
console.log(notes.get(navika));
console.log(notes.has(advitha));
notes.delete(advitha);
console.log(notes.has(advitha));
try {
notes.set("Srihitha", "string key");
} catch (err) {
console.log(err.name + ": " + err.message);
}Pays by check
true
false
TypeError: Invalid value used as weak map keyExplanation: the API looks like a Map's, but keys must be objects: a string key throws. There is no notes.size and no way to loop over the entries.
Why No Size or Iteration
The garbage collector runs whenever the engine decides, so the contents of a WeakMap can change at any moment without your code doing anything. If you could read size or loop over the entries, your program's behavior would depend on garbage collection timing, which is unpredictable. So the language simply doesn't offer those operations: you can only ask about a key you already have, and if you have it, it's still alive.
Private Data per Object
Before classes had #private fields (ES2022), WeakMaps were the standard way to give objects truly private data. You'll see this pattern in libraries:
const balances = new WeakMap();
function createAccount(owner, opening) {
const account = {
owner,
pay(amount) {
balances.set(account, balances.get(account) - amount);
},
describe() {
return `${owner} owes $${balances.get(account)}`;
},
};
balances.set(account, opening);
return account;
}
const account = createAccount("Srihitha", 450);
account.pay(200);
console.log(account.describe());
console.log(account.balance, Object.keys(account));Srihitha owes $250
undefined ['owner', 'pay', 'describe']The balance isn't a property of the account at all, so nothing outside the module can read or change it. When an account is discarded, its balance entry is collected with it. Today, classes with #balance fields do this more directly (see the class members lesson).
Caching Results per Object
A WeakMap is a natural cache for results computed from an object:
const summaryCache = new WeakMap();
let computed = 0;
function summary(student) {
if (!summaryCache.has(student)) {
computed++;
const total = student.payments.reduce((a, b) => a + b, 0);
summaryCache.set(student, `${student.name}: $${total}`);
}
return summaryCache.get(student);
}
const advitha = { name: "Advitha", payments: [45, 200] };
console.log(summary(advitha), summary(advitha), computed);Advitha: $245 Advitha: $245 1If advitha is later removed from the app, the cached summary is freed too. With a Map, it would stay forever unless you remembered to delete it. (If the student's payments can change, you still need to delete the cache entry when they do.)
Using a WeakSet
A WeakSet holds objects weakly and only answers "is this object in the set?". It is used to mark objects:
const processed = new WeakSet();
function processOnce(payment) {
if (processed.has(payment)) return `Skipped payment ${payment.id}`;
processed.add(payment);
return `Processed payment ${payment.id}`;
}
const p1 = { id: 1, amount: 120 };
console.log(processOnce(p1));
console.log(processOnce(p1));
console.log(processOnce({ id: 1, amount: 120 }));Processed payment 1
Skipped payment 1
Processed payment 1The third call passes a different object with the same contents, so it isn't in the set. WeakSets track object identity, not data.
Common Mistakes
Using primitives as keys. Strings and numbers throw. Use a regular Map for primitive keys.
Expecting to list the contents. There is no iteration or size. If you need them, use a Map and delete entries yourself.
Testing garbage collection in code. You can't observe when entries disappear, and you shouldn't try.
Using a WeakMap where the key is a string ID. IDs are primitives; the entry would never be weak. Key by the object itself.
Practice
Challenge: Write countVisits(obj) that returns how many times it has been called with that same object, using a WeakMap so visited objects aren't kept alive.
Show solution
const visits = new WeakMap();
function countVisits(obj) {
const count = (visits.get(obj) ?? 0) + 1;
visits.set(obj, count);
return count;
}
const page = { url: "/fees" };
console.log(countVisits(page), countVisits(page), countVisits(page));
console.log(countVisits({ url: "/fees" }));1 2 3
1Key Takeaways
| Collection | Methods | Use for |
|---|---|---|
WeakMap | get, set, has, delete | Data attached to objects |
WeakSet | add, has, delete | Marking objects |
Map / Set | Full API, iterable | Everything else |
Was this tutorial helpful?