4

How to make weak set or weak map "iterable" in ES6 so that i can use for in loop :

for(item in weakMap){console.log(item); }
  • What's wrong with [`for...of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) – Tushar Apr 21 '16 at 05:23
  • If you want to use `for...in` then use Object. – Tushar Apr 21 '16 at 05:23
  • 4
    weak map/set are not iterable – Walter Macambira Apr 21 '16 at 05:26
  • 1
    We can store the keys in an Iterable and iterate them to retrieve the values in the WeakMap. Some of them might be undefined; One obvious caveat: the keys are not garbaged collected This can be packaged as IterableWeakMap. In my humble opinion, this question is different from the one already answered. We are not asking "Why" they are not iterable. We are asking suggestions on what it takes to build an object where the values are stored in a WeakMap but we can still iterate them. – hmalphettes Aug 19 '16 at 03:54
  • This is a "how" question. It cannot be a duplicate of a "why" question. Voted to reopen. – Parzh from Ukraine Aug 19 '22 at 12:01

1 Answers1

5

No the contents of a WeakMap are not accessible by design, and there is no iterability.

A key property of Weak Maps is the inability to enumerate their keys. This is necessary to prevent attackers observing the internal behavior of other systems in the environment which share weakly-mapped objects. Should the number or names of items in the collection be discoverable from the API, even if the values aren't, WeakMap instances might create a side channel where one was previously not available.

Source

ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • 1
    Looks like JavaScript will finally be getting a _true_ WeakReference implementation in the future! https://stackoverflow.com/a/58009243/2441655 This would enable an iterable WeakMap, by combining the two. (create an array of WeakRefs to each of the keys in the WeakMap, then iterate the WeakMap by iterating through the array of keys, and combining each with the `map.get(key)` value) – Venryx Nov 16 '19 at 10:05
  • 1
    Firefox Nightly has added experimental support for WeakRef. Here's an example implementation using it to create an iterable version of WeakSet: https://gist.github.com/seanlinsley/bc10378fd311d75cf6b5e80394be813d – seanlinsley Mar 21 '20 at 21:05