liveBook · Manning

WeakMap

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A JavaScript key-value collection whose keys are held weakly, so key objects do not prevent garbage collection and the collection is not iterable.

A WeakMap is a non-iterable key-value collection whose keys must be objects. Its weak references do not keep keys from becoming eligible for garbage collection; accessing a key’s value requires a reference to that key. section 25.4

Keep these limits in mind:

  • You cannot iterate a WeakMap or list its keys. section 25.4
  • You cannot check for a particular key unless you already have a reference to it. section 25.4
  • Use a regular Map instead when you need iteration; remove entries when their objects are no longer needed. section 25.4

Metadata for short-lived objects

A WeakMap can associate metadata with logged-in player objects or DOM nodes. When those objects are no longer referenced elsewhere, the WeakMap does not keep them from being garbage-collected. section 25.4

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Defines weak keys, object-only keys, and non-iterability, but gives no worked WeakMap code.
Examples
Uses logged-in player objects and DOM nodes as examples of objects that may need metadata.
What you can do after
Apply WeakMap to associate object metadata when iteration is unnecessary and avoiding retained keys matters.
How it connects
Contrasts WeakMap with Map and WeakSet, and relates weak keys to garbage collection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.