zerkms zerkms - 14 days ago 4
Javascript Question

Would a "circular" reference be treated as "reachability" for a WeakMap?

function f() {
const w = new WeakMap();
const o = {};

w.set(o, { v: o });

return w;

const weakMap = f();

For the given code, would the only
item considered as reachable or not? Hence, will it be garbage collected or not?

PS: This question is asked from the perspective of the specification, not particular implementations.


Quoting WeakMap Objects section,

If an object that is being used as the key of a WeakMap key/value pair is only reachable by following a chain of references that start within that WeakMap, then that key/value pair is inaccessible and is automatically removed from the WeakMap.

In your case, the only way to reach o would be to start from one of the keys in the weakMap, as there is no external references to it. So, it would be considered as inaccessible.

WeakMap implementations must detect and remove such key/value pairs and any associated resources.

So, it would be eventually garbage collected.