JavaScript WeakMap and WeakSet
Introduction
WeakMap and WeakSet are similar to Map and Set, but they have key differences that make them useful in specific situations.
Key Characteristics of WeakMap and WeakSet
- Keys in
WeakMapand values inWeakSetmust be objects (not primitives like numbers, strings, or booleans). - Garbage collection-friendly: If an object key/value is no longer referenced elsewhere, it is automatically removed from the
WeakMaporWeakSet. - No size property or iteration methods: Unlike
MapandSet, they cannot be iterated over or checked for size.
JavaScript WeakSet
A WeakSet is similar to a Set, but it only stores objects and automatically removes them when they are no longer referenced elsewhere.
Creating a WeakSet
Adding Objects to a WeakSet
Checking if an Object Exists
Removing an Object
Automatic Garbage Collection
If user2 is set to null and is not referenced anywhere else, it will be removed from weakSet automatically.
🔸 No way to check size:
Unlike Set, WeakSet does not have .size because its elements can be garbage collected at any time.
JavaScript WeakMap
A WeakMap is similar to a Map, but keys must be objects, and it allows automatic garbage collection.
Creating a WeakMap
Adding Key-Value Pairs
Checking If a Key Exists
Removing a Key
Automatic Garbage Collection
If the person object is set to null, it is automatically removed from the WeakMap.
🔸 No .size, .keys(), or .values()
WeakMaps do not support iteration or size checking because their keys can be garbage collected at any time.
Differences Between WeakMap and Map
| Feature | Map | WeakMap |
|---|---|---|
| Keys | Any type (objects, strings, numbers, etc.) | Objects only |
| Garbage Collection | No automatic removal | Removes entries when keys are no longer referenced |
| Iteration | Yes (.keys(), .values(), .entries()) | No iteration methods |
.size Property | Yes | No |
Differences Between WeakSet and Set
| Feature | Set | WeakSet |
|---|---|---|
| Values | Any type | Objects only |
| Garbage Collection | No automatic removal | Automatically removes unreferenced objects |
| Iteration | Yes (forEach(), for...of) | No iteration methods |
.size Property | Yes | No |
When to Use WeakMap and WeakSet?
✅ WeakMap:
- Storing metadata about objects (caching, tracking elements in the DOM)
- Keeping data private (since WeakMap keys cannot be accessed directly)
✅ WeakSet:
- Keeping track of unique objects without preventing garbage collection
Summary
✔ WeakMap and WeakSet store only objects
✔ They automatically remove unreferenced objects
✔ They do not have iteration methods or .size
✔ WeakMap is useful for caching and private data storage
✔ WeakSet is useful for tracking unique objects
Now you know how to use WeakMap and WeakSet in JavaScript! Let me know if you need more examples.

