r/learnjavascript • u/Defiant_Help5416 • Aug 01 '25
Weakset use cases
Weakset use cases in JavaScript ??
1
u/shgysk8zer0 Aug 01 '25
I feel like I have a few examples but I can't really think of any right now besides preventing duplicate operations on cyclical references. It's something I know I've wanted to use often but usually the inability to iterate over them is a barrier to what I need, so I have to go for a Set and think of a way to remove them when needed.
Another related thing is just keeping track of some nodes/elements. I know I've wanted a basic set of them that is cleaned up when something is removed a few times. Can't remember specifics though.
But I know I use WeakMap a lot more.
0
u/Caramel_Last Aug 01 '25
Mostly you don't need it, but its main purpose is to break a cycle of reference
Normally GC can collect cyclically referenced objects as long as: none of the references in the cycle is referenced anymore
However, if one of the reference is constantly in the memory, the whole cycle will stay in the memory forever. The only way to break this is to change the main reference into a weak reference. WeakMap and WeakSet are collections built on top of this WeakRef
4
Aug 01 '25
[removed] — view removed comment
2
u/Defiant_Help5416 Aug 06 '25
Thanks a lot! That example really helped me understand when to use
WeakSetinstead ofSet. I appreciate the clear explanation and the real-world context!1
u/Caramel_Last Aug 01 '25
The dom example is a clear good usage of weakref. I'll also add ORM implementation as a possible use case. Basically when the lifetime of object is managed by external system, such as dom ( the c++ in the browser manages it ), or ORM( the DB manages it ), then it's a potential usecase of weakref
1
1
u/shuckster Aug 01 '25
data-link-to-spa-route
You mean an anchor-tag with an href?
1
2
u/PatchesMaps Aug 01 '25
It's niche but detecting circular references is one. There are many other use cases out there but again, it's niche so I wouldn't be surprised if there are many many senior devs out there that have never needed to use it before.