In MDN article on WeakSets, an example is given for using weak sets to avoid infinite recursion on circular references:

// Execute a callback on everything stored inside an object
function execRecursively(fn, subject, _refs = new WeakSet()) {
  // Avoid infinite recursion
  if (_refs.has(subject)) {
  // ...

If WeakSet is intended to allow the objects to be garbage collected, doesn’t this mean that with sufficiently large objects and little memory a previously encountered object will be garbage collected and thus set’s .has() will not return true, making infinite recursion possible?

1 Answer 1


WeakSet only allows garbage collection of objects which are not referenced anywhere else, i.e. if the reference in the WeakSet is the only remaining reference.

If the object is referenced as part of some other data structure, it will not be garbage collected. If that structure gets too big, you will just get an "out of memory"-error.

  • This would require that in execRecursively(fn, subject[key], _refs); line of the example, that subject will survive for all subsequent (possibly recursing many times) runs of the function… Which I guess would be the case. If so, I can see why weak sets are acceptable for this case. Jul 15 at 8:55
  • I still don’t see why the article says they are “ideal” for this use case: since the code manually deletes the subject from the weak set after that recursive call, I can’t see how it is different from using a regular set… Jul 15 at 8:58
  • 2
    @AntonStrogonoff: You are correct. As far as I can tell, you might just as well have used a regular Set for this. The MDN text alludes to WeakSet being more performant for this case, probably because it doesn't need to keep track of the insertion order like a Set needs. But this is unrelated to garbage collection.
    – JacquesB
    Jul 15 at 9:07
  • I see, thanks for clarifying. Jul 15 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.