0

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)) {
    return;
  }
  // ...

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 Answers1

2

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.

JacquesB
  • 61,955
  • 21
  • 135
  • 189