Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are WeakMaps not interable? [duplicate]

Javascript now has classes called WeakMap and WeakSet, where the keys are weakly referenced.

Why may instances of these not be iterated over, i.e. using WeakMap#entires?

Note: this isn't a duplicate question. The other one asks "how" and this asks "why".

like image 226
Lolums Avatar asked Dec 02 '25 10:12

Lolums


1 Answers

MDN explains this with

If they were, the list would depend on the state of garbage collection, introducing non-determinism.

But you probably wonder what that really means.

First of, garbage collection is non-deterministic. A JavaScript program may be garbage collected by the garbage collector at the sole discretion of the environment in which it runs.

Now imagine we have the following program:

const weakMap = new WeakMap();

const key1 = { data: 123 };
weakMap.set(key1, "value");
weakMap.set({ data: 456 }, "value");

for (const [key, value] of weakMap) {  // This does not actually work, of course
  console.log(`${key} is ${value}`);
}

What would you expect this program to produce?

We cannot tell because actually the object created by { data: 456 } would only be referenced in our map. So this entry is to be deleted by the garbage collector. But we cannot be sure (and it is even somewhat unlikely) that the garbage collector has already removed it from the map when iterating over it. On the other hand, it might indeed have already removed it.

This program would exhibit unpredictable behaviour and is therefore not allowed.

like image 155
idmean Avatar answered Dec 04 '25 22:12

idmean



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!