Map vs WeakMap: what's the difference?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
A Map holds its keys strongly — as long as the map exists, the keys cannot be garbage collected. A WeakMap holds them weakly: if nothing else references a key, the entry disappears automatically.
let node = document.querySelector("#row");
const strong = new Map();
strong.set(node, { clicks: 0 });
const weak = new WeakMap();
weak.set(node, { clicks: 0 });
node.remove();
node = null;
// strong still holds the element — it cannot be collected (a leak)
// weak lets it go, and the entry vanishes with it
That difference drives everything else.
Map / Set | WeakMap / WeakSet | |
|---|---|---|
| Key types | Anything | Objects and symbols only |
| Reference strength | Strong | Weak |
| Iterable | Yes | No |
size | Yes | No |
clear() | Yes | No |
Why the weak versions cannot be iterated
Entries can disappear at any moment when the collector runs, so listing them would be non-deterministic — the same loop could give different results on two runs. Removing iteration and size keeps garbage collection unobservable from JavaScript.
Where each fits
Use Map for ordinary key-value data you need to read back, count or iterate.
Use WeakMap to attach information to objects you do not own, where the metadata should die with the object:
const meta = new WeakMap();
function track(el, data) {
meta.set(el, data); // no cleanup code needed later
}
Typical cases are caching computed results per object, storing private data for a class instance, and keeping state for DOM nodes without leaking when they are removed.
The rule of thumb: if you would otherwise need to remember to delete the entry, a WeakMap removes that obligation.
