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?