1

From what I know about native JavaScript WeakMaps, they store their keys weakly, but store their values strongly, is that correct?

If so, would using a value as both, a key and a value in a WeakMap prevent the object from being garbage-collected?

const domElement0 = ...;
const domElement1 = ...;

const map = new WeakMap([
    [ domElement0, domElement1 ],
    [ domElement1, domElement0 ]
]);

Assuming that the WeakMap is always available, in that snippet, I would assume that, if domElement0 is unreachable, then domElement1 would not be garbage-collected, and vice versa, but if they both become unreachable and detached from the DOM, can I know that they will both become eligible for GC in most browsers?

If so, can someone provide a reference to why this is possible?

  • Possible duplicate of [Two-way WeakMap keeping objects alive?](https://stackoverflow.com/q/72391188/1048572) – Bergi Nov 20 '22 at 17:17

1 Answers1

1

I think they should become garbage.

The specification of WeakMap Objects has the following note:

WeakMap and WeakSets are intended to provide mechanisms for dynamically associating state with an object in a manner that does not “leak” memory resources if, in the absence of the WeakMap or WeakSet, the object otherwise became inaccessible and subject to resource reclamation by the implementation's garbage collection mechanisms.

So if the only references to the objects are through a WeakMap entry, and the keys are not accessible through some chain of references starting outside the WeakMap, the objects become garbage.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I want to believe the same, but I can't find anything that talks about the *values* that the map holds. If they are strongly held, couldn't an implementation technically leave them in memory? –  Nov 30 '20 at 02:09
  • I think this is essentially a quality of implementation issue, since memory use is not visible in the behavior of the program itself. – Barmar Nov 30 '20 at 03:31