0

I've read that WeakMap and WeakSet don't support working with the entire data collection at once, which means that keys(), values(), entries(), size() and loops are inaccessible for these type of collections. It's written that the reason of that behaviour is that the developer cannot know exact moment when the garbage collector will work.

The source

...technically it’s not exactly specified when the cleanup happens. The JavaScript engine decides that. It may choose to perform the memory cleanup immediately or to wait and do the cleaning later when more deletions happen.

How do I see this? For example, the first element in the WeakMap/WeakSet data collection has been removed. But it may happen that the garbage collector hasn't cleared it from the storage yet. Hence, deleted element can be used in loops, methods that work with whole collection. To avoid this behaviour, all of these methods and loops aren't supported by these data collections.

let weakMap = new WeakMap();
let obj = {};
//adding some elements
weakMap.set(obj, 255);
weakMap.set({name: `Rita`}, `Rita`);
//deleting the first element
obj = null;

//we can't use loops for the whole collection 
//why? because deleted element with `obj` key can still exist in data storage
weakMap.get(obj); //it's theoretically possible that deleted element with `obj` key still 
//exists in the data storage, garbage collector hasn't reached it yet 

It's completely understandable. But what about referring to a single element? By the way, it's completely allowed for these type of collections. But, in fact, we also don't know exact moment when the garbage collector will work. As I see, it means that element can be deleted, but because of the fact that garbage collector hasn't reached it yet, it still can be displayed.

It turns out that limited functionality of these collections cannot secure bugs in the form of output of deleted elements? Am I correct?

Ivan
  • 478
  • 2
  • 13
  • `weakMap.get(obj)` will be `weakMap.get(null)`, so there is zero chance it will ever return you `255`. – VLAZ Jun 15 '22 at 17:44
  • @VLAZ then why do this element can possibly be displayed with loops and methods that work with entire collection? – Ivan Jun 15 '22 at 17:51
  • 1
    If you try to use `.get()` with the actual object, then it will work. But your current code doesn't do that - assigns `null` to `obj` then uses `obj` to fetch a value. It's unclear what you expect to happen. But if you have no reference to an object (which will make it eligible for GC) then you cannot fetch it from the weak map. In theory it might linger for a bit more before GC runs but that's not very relevant, since you have no remaining references, thus no way to use it as a key. – VLAZ Jun 15 '22 at 17:56

0 Answers0