The following four data structures are new in ECMAScript 6: Map, WeakMap, Set and WeakSet.

The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced.

Keys of WeakMaps are of the type Object only. Primitive data types as keys are not allowed (e.g. a Symbol can't be a WeakMap key).

WeakMaps work mostly like Maps, with the following differences:

  • WeakMap keys are objects (values can be arbitrary values)
  • WeakMap keys are weakly held
  • You can’t get an overview of the contents of a WeakMap
  • You can’t clear a WeakMap
var weakmap = new WeakMap()
weakmap.set({}, 123);

var weakmap1 = new WeakMap()
weakmap1.set(1, "One"); // TypeError: Invalid value used as weak map key

Why WeakMap?

The experienced JavaScript programmer will notice that this API could be implemented in JavaScript with two arrays (one for keys, one for values) shared by the four API methods.

Such an implementation would have two main inconveniences.

  • The first one is an O(n) search (n being the number of keys in the map).
  • The second one is a memory leak issue.

With manually written maps, the array of keys would keep references to key objects, preventing them from being garbage collected. In native WeakMaps, references to key objects are held "weakly", which means that they do not prevent garbage collection in case there would be no other reference to the object.

Because of references being weak, WeakMap keys are not enumerable (i.e. there is no method giving you a list of the keys). If they were, the list would depend on the state of garbage collection, introducing non-determinism.