WeakMap & WeakSet
JavaScript's regular Map and Set keep their keys
and values alive forever — even after every other reference to those objects is gone.
WeakMap and WeakSet solve this by holding only
weak references to their object keys — allowing the garbage collector to reclaim
memory the moment those objects are no longer needed elsewhere. They are
the go-to tool for storing metadata about objects without leaking memory.
Three Things to Know Before You Start
WeakMap and WeakSet are specialised versions of Map and Set. Before diving into the API, understand the three foundational ideas that explain every design decision:
Strong vs Weak References
The fundamental difference is whether a reference keeps an object alive
in memory. A regular Map holds strong references — its keys and values
will never be garbage-collected as long as the Map itself exists. A WeakMap
holds weak references — keys can be reclaimed once no strong reference to them remains:
const cache = new Map();
let obj = { id: 1 };
cache.set(obj, "data");
obj = null; // ❌ object NOT collected — Map still holds strong ref
// ── WeakMap lets GC reclaim the object ────────────────────
const wCache = new WeakMap();
let obj2 = { id: 2 };
wCache.set(obj2, "data");
obj2 = null; // ✅ object IS eligible for GC — WeakMap won't stop it
WeakMap API
WeakMap has a deliberately minimal API — just four methods. There is no
size property and no way to iterate over entries, because
the set of live entries is non-deterministic (it depends on when the GC runs):
undefined if not present.
true if
key exists in the WeakMap.
true if the key was present.
true if
the object is currently in the set.
true if it was present.
size, no
forEach, no keys(), no values() — WeakSet is
intentionally non-iterable.
// ── WeakMap ──────────────────────────────────────────────────
const wm = new WeakMap();
const keyA = {}; // key must be an object
const keyB = {};
wm.set(keyA, "value for A");
wm.set(keyB, 42);
wm.get(keyA); // "value for A"
wm.has(keyB); // true
wm.delete(keyB); // true
wm.has(keyB); // false
// ❌ Primitives are NOT allowed as keys
wm.set("string", 1); // TypeError!
// ── WeakSet ──────────────────────────────────────────────────
const ws = new WeakSet();
const nodeA = document.createElement("div");
const nodeB = document.createElement("span");
ws.add(nodeA);
ws.add(nodeB);
ws.has(nodeA); // true
ws.delete(nodeB); // true
ws.has(nodeB); // false
size, forEach, keys(),
and values() to prevent this. If you need iteration, use a regular
Map or Set.
WeakMap vs Map — Full Comparison
Use this table to quickly decide which collection to reach for:
| Feature | Map | WeakMap |
|---|---|---|
| Key types | Any value | Objects only |
| Reference type | Strong — keeps key alive | Weak — allows GC |
| size property | ✓ Yes | ✕ No |
| Iteration | ✓ forEach, keys, values, entries | ✕ Not iterable |
| clear() | ✓ Yes | ✕ No |
| Memory leaks | Risk if keys accumulate | None — entries auto-evict |
| Best for | General-purpose key/value store | Metadata keyed by object lifetime |
| Feature | Set | WeakSet |
|---|---|---|
| Value types | Any value | Objects only |
| Reference type | Strong | Weak — allows GC |
| size property | ✓ Yes | ✕ No |
| Iteration | ✓ forEach, for...of | ✕ Not iterable |
| Best for | Unique value collections | Tagging objects without preventing GC |
Pattern — Private Data with WeakMap
Before ES2022 private class fields (#field), the standard
pattern for truly private instance data was a module-scoped WeakMap. The key is
the instance; the value is an object holding all private state:
// ❌ PROBLEM: using a closure-per-instance wastes memory
function Counter() {
let _count = 0; // closure var — one copy per instance
this.inc = () => _count++;
this.get = () => _count;
}
// ✅ Module-scoped WeakMap — private data, auto-cleaned on GC
const _private = new WeakMap();
class BankAccount {
constructor(owner, balance) {
_private.set(this, { owner, balance });
}
deposit(amount) {
if (amount <= 0) throw new RangeError("Must be positive");
_private.get(this).balance += amount;
}
getBalance() {
return _private.get(this).balance;
}
getOwner() {
return _private.get(this).owner;
}
}
const acc = new BankAccount("Alice", 1000);
acc.deposit(500);
acc.getBalance(); // 1500
acc.balance; // undefined — truly private!
// When acc goes out of scope, _private entry is GC'd automatically
#balance) are now the
preferred way to write private data in new code — they are part of the language syntax
and slightly simpler. The WeakMap pattern is still useful when you need to share
private state across multiple cooperating classes or functions in the same module.
Key Method Reference
The complete API for both collections is tiny by design — here is every method with a one-line explanation:
[key, value] pairs where keys are objects (e.g., entries from
another Map).
value with key.
key must be an object or a non-registered Symbol — passing a
primitive throws a TypeError. Returns the WeakMap for
chaining.
key, or
undefined if the key is not present (or has already been
garbage-collected).
true if key is currently
in the WeakMap — false otherwise. Useful as a guard before calling
get().
key. Returns
true if the key was present, false otherwise.
Typically unnecessary — entries self-evict when the key is GC'd.
value (must be an object) to the set.
Duplicate adds are silently ignored — like regular Set. Returns the WeakSet
for chaining.has returns a boolean indicating membership.
delete removes the value and returns true if it was
present. Neither throws if the value has already been garbage-collected.
Real-World Use Cases
These are the everyday scenarios where WeakMap and WeakSet genuinely outperform their regular counterparts:
this. Data is inaccessible outside the module and auto-cleared
when the instance is GC'd.
ws.has(obj) to verify an object was
created by your code, not forged by a caller.wm.has(obj) returns false naturally.
Try It — Live Editor
Experiment with WeakMap below. The demo shows a DOM-node metadata cache — each button click creates a node, stores metadata in a WeakMap, then removes the node to let GC reclaim both the node and its WeakMap entry.
Common Patterns
Three patterns you'll encounter WeakMap and WeakSet used for in real codebases:
// Deep-clone an object, safely handling circular references
function deepClone(obj, seen = new WeakSet()) {
if (obj === null || typeof obj !== "object") return obj;
if (seen.has(obj)) return "[Circular]";
seen.add(obj);
const clone = Array.isArray(obj) ? [] : {};
for (const key of Object.keys(obj)) {
clone[key] = deepClone(obj[key], seen);
}
return clone;
}
const a = { x: 1 };
a.self = a; // circular ref!
deepClone(a); // { x: 1, self: "[Circular]" }
// Verify objects were created by YOUR factory, not forged
const _trusted = new WeakSet();
function createUser(name, role) {
const user = Object.freeze({ name, role });
_trusted.add(user); // brand it
return user;
}
function isValidUser(obj) {
return _trusted.has(obj); // check brand
}
const alice = createUser("Alice", "admin");
const fake = { name: "Hacker", role: "admin" }; // forged
isValidUser(alice); // true ✅
isValidUser(fake); // false ✅
// Cache results keyed by object argument — entries auto-evict
const cache = new WeakMap();
function processElement(el) {
if (cache.has(el)) {
console.log("cache hit");
return cache.get(el);
}
const result = {
rect: el.getBoundingClientRect(),
styles: getComputedStyle(el),
};
cache.set(el, result); // store result
return result;
}
// When the element is removed from the DOM and GC'd,
// the cache entry disappears automatically — no Map.clear() needed.
WeakMap?WeakMap and WeakSet not
have a size property or iteration methods?- A weak reference does not prevent garbage collection. Once the only reference to an object is a WeakMap key or WeakSet member, that object can be reclaimed — and the entry disappears automatically.
- WeakMap stores key/value pairs where keys must be objects (or
non-registered Symbols). API:
set,get,has,delete— nothing else. - WeakSet stores a collection of unique objects. API:
add,has,delete— nothing else. - Neither collection has
size,forEach, or iteration methods — entries can vanish at any time during GC, making a consistent snapshot impossible. - Choose WeakMap over
Mapwhen keys are objects with their own lifetime and you want zero memory-leak risk. ChooseMapwhen you need to iterate, count, or use primitive keys. - Classic WeakMap pattern: private class data — store instance-private
state in a module-scoped WeakMap keyed by
this. - Classic WeakSet patterns: cycle detection (deep clone / serialise), object branding (verify trusted origin), and visited-node tracking in graph algorithms.
- ES2022 private class fields (
#prop) replace the WeakMap private-data pattern for most new code — but WeakMap remains superior when sharing private state across multiple cooperating classes.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.