JavaScript WeakSet
Subject: JavaScript
A WeakSet is a special type of Set in JavaScript that stores only objects and holds them weakly, meaning the objects can be garbage collected if there are no other references to them.
Key Characteristics
- Only objects are allowed as values (no primitives).
 - Objects are stored as weak references.
 - WeakSet is not iterable (no loops).
 - It does not have .size, .keys(), .values(), or forEach() methods.
 - Ideal for managing temporary object memberships like caching or access control.
 
Syntax
Example 1: Basic Usage
Example 2: Use Case – Tracking Active DOM Elements
If div is removed from the DOM and no other references exist, it will be garbage collected along with its entry in the WeakSet.
Important Differences: WeakSet vs Set
- WeakSet stores only objects as weak references; Set can store any type and maintains strong references.
 - WeakSet is not iterable and lacks size or iteration methods; Set supports iteration and size property.
 
Key Takeaways
- WeakSet holds only object references without preventing garbage collection.
 - Useful for temporary or private tracking of objects.
 - Designed for memory-efficient object tracking in libraries, frameworks, and reactive systems.
 - Does not support iteration or primitive values.