JavaScript WeakSet
JavaScript WeakSet
A WeakSet is similar to a normal Set, but with some important differences. It stores only objects (not numbers, strings, or other primitives), and it allows objects to be garbage-collected when no longer referenced.
WeakSets are useful when you want to track objects temporarily without preventing them from being removed from memory.
✅ Key Characteristics of WeakSet
| Feature | WeakSet | Set |
|---|---|---|
| Stores only objects | ✔ Yes | ❌ No (can store any type) |
| Allows garbage collection | ✔ Yes | ❌ No |
| Iterable | ❌ No | ✔ Yes |
| Methods supported | add(), has(), delete() |
Many |
| Size property | ❌ No | ✔ Yes |
🧩 Creating a WeakSet
➕ Adding Values (Only Objects Allowed)
❌ Removing Values
🧠 Garbage Collection Example
If an object stored in WeakSet no longer has references elsewhere, it is removed automatically from memory.
⚠ Limitations of WeakSet
WeakSet is not iterable, so you cannot loop through it:
📌 When to Use WeakSet?
Use it when you want to track objects without preventing memory cleanup, such as:
-
Caching objects temporarily
-
Marking objects as processed
-
Tracking DOM element states
✔ Practical Example: Tracking DOM Elements
📝 Summary
| Action | WeakSet Support |
|---|---|
| Add items | ✔ add() |
| Remove items | ✔ delete() |
| Check item exists | ✔ has() |
| Iterate items | ❌ No |
| Primitive values allowed | ❌ No |
