JavaScript WeakSet

JavaScript Tutorial

JavaScript WeakSet

A JavaScript 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

FeatureWeakSetSet
Stores only objects Yes No (can store any type)
Allows garbage collection Yes No
Iterable No Yes
Methods supportedadd(), 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

ActionWeakSet Support
Add itemsadd()
Remove itemsdelete()
Check item existshas()
Iterate items No
Primitive values allowed No

You may also like...