The ES6 WeakMap and WeakSet classes

Along with the two new data structures Set and Map, ES6 also introduced a weak type version of these classes: WeakMap and WeakSet.

Basically, the only difference between the Map or Set classes and their Weak versions are:

  • The WeakSet or WeakMap classes do not have the entries, keys, and values methods
  • It is only possible to use 0bjects as a key

The reason for creating and using these two classes is performance related. As WeakSet and WeakMap are weakly typed (using object as a key), there is no strong reference to the keys. This behavior allows the JavaScript garbage collector to clean an entire entry from the map or set.

Another advantage is that you can only retrieve a value if you have its key. As these classes ...

Get Learning JavaScript Data Structures and Algorithms - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.