24

A javascript WeakMap ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap ) does not allow you to get the key, or the length or size, by design.

Is it possible to nevertheless loop over entries in some way ?

If not .. how does the Chrome console do this ?

enter image description here

commonpike
  • 8,507
  • 3
  • 56
  • 56

2 Answers2

33

Is it possible to nevertheless loop over entries in some way?

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

If not … how does the Chrome console do this?

The console uses the debugging API of the JS engine, which allows access to the internals of objects (also to promise states, wrapped primitives, etc.) and many more.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • 1
    Ever since I read this answer, I started noticing more strange magic in the chrome console. There are rare situations where the console, when trying to trace code, can output data from the future, too :-) – commonpike May 31 '16 at 12:48
  • 2
    @commonpike: That particular behaviour is explained [here](http://stackoverflow.com/q/23392111/1048572). – Bergi May 31 '16 at 14:23
  • 2
    Those look like values from the future relative to the past but not further than the present. :} – trusktr Mar 21 '17 at 05:51
4

Things are moving and it will soon be possible to create iterable week maps thanks to weak refs. See the iterable WeakMap example in the tc39 weakrefs proposal.

(note that it is already possible with nodejs v12.?.? using --harmony-weak-refs flag)

Franck Freiburger
  • 21,662
  • 20
  • 60
  • 90