Example with "nulling" value. Why does the element still exist in the WeakMap collection in this case?
let weakMap = new WeakMap();
let obj = {name: 'Ivan'};
//adding some new element
weakMap.set({}, obj);
obj = null;
console.log(weakMap);
console.log(weakMap.get({}));
Whole collection
One element
Example with "nulling" key:
What's going on here? What does it come from? The garbage collector does not have time to clean up everything or what?



First of all
weakMap.set({}, obj);andweakMap.get({});will never refer to the same element in the WeakMap because they are separate, anonymous object literals. In order for the WeakMap to be useful you need to store a reference to the object to be used as key1.Secondly, it is the key that is weakly referenced in the WeakMap, not the value, so setting the value to
nullwill have no effect on the WeakMap. Instead you need to 'null' the key2 (another reason you need a stored reference to it).1 Your example using an unreachable object as key will disappear from the WeakMap on garbage collection, but not because you set
obj=nullbut because the only reference to the object exists in the WeakMap.2 There is no good way to demonstrate the behaviour of the second snippet because, per the documentation, '... a WeakMap doesn't allow observing the liveness of its keys, its keys are not enumerable.' Nonetheless, debugging in the console will reveal the behaviour, though awkwardly given the variety of ways different browsers treat objects in the console, ie. chrome's live objects.