javascriptgarbage-collectionweak-referencesweakmap

Will WeakSet be garbage collected if values are used as keys in Map?


I have some HTML elemenets that are used as keys in ES6 Maps, I also have a "WeakSet" which contains those same HTML elements as values, now those HTML elements will eventually be removed from DOM by some other functionality, will then they be garbage collected by WeakSet, even though they are still used as keys in Map?


Solution

  • No, they will not be garbage-collected as long as they are part of the Map (and the map itself is not garbage-collected). You can still access them by iterating the map .keys(). Subsequently, they will still be part of the WeakSet (as long as the set itself is not garbage-collected).

    To avoid this, use a WeakMap instead of a Map, it will not hold on the keys.