Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to WeakMap items

Tags:

javascript

Why is there no direct access to items in WeakMap? And when the garbage collector deletes the link that is the key to WeakMap then also the value that was tied to this key is deleted?

like image 595
Andry Holovchak Avatar asked Feb 01 '26 23:02

Andry Holovchak


1 Answers

By "direct access to items", I assume you mean why they are not enumerable? Here's the MDN explanation:

Because of references being weak, WeakMap keys are not enumerable (i.e. there is no method giving you a list of the keys). If they were, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a Map.

I am not sure I understand the second part of the question. An entry (i.e. key-value pair) is eligible to be deleted from the WeakMap if there are no non-weak references to the key. What happens to the value would be the same as what happens if it were deleted from Map, or from anywhere else: if it was the last non-weak reference to that value, it becomes eligible for garbage collection. However, as long as the entry (the key-value pair) is surviving in a WeakMap, the value is considered to be referenced, and will not be garbage-collected.

like image 93
Amadan Avatar answered Feb 04 '26 12:02

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!