WeakMap vs Map in JavaScript
Map holds strong references to its keys, keeping them in memory as long as the Map exists; WeakMap holds weak references, allowing its keys to be garbage col...
Published November 21, 2026
A Map holds strong references to its keys, so entries stay until you delete them; a WeakMap only accepts objects as keys and holds them weakly, letting the garbage collector remove entries when the key object is no longer used elsewhere.
The concept
WeakMap cannot be iterated, has no size and no clear(), because entries may disappear at any time.
It is ideal for attaching private or cached data to objects (DOM nodes, instances) without causing memory leaks.
What happens when the key is dropped
let el = {}; map.set(el, 'x'); weak.set(el, 'x'); el = null
Map → still holds the object (leak)
WeakMap → entry can be garbage collected
Practical examples
Private data per object
const secrets = new WeakMap()
class User { constructor(pw) { secrets.set(this, pw) } check(p) { return secrets.get(this) === p } }Cache by object
const cache = new WeakMap()
function heavy(obj) { if (!cache.has(obj)) cache.set(obj, compute(obj)); return cache.get(obj) }Only objects as keys
new WeakMap().set('str', 1) // TypeErrorCommon mistakes
- Using WeakMap when you need to iterate or count.
- Using primitives as keys.
- Expecting entries to disappear immediately.
Key takeaways
- Weak references to object keys.
- No iteration or size.
- Prevents leaks for per-object metadata.
FAQ
What is WeakSet?
A set of objects held weakly.
WeakRef?
A reference that does not stop garbage collection of its target.