11. Map and WeakMap

An object is made of keys (always strings) and values, whereas in Map, any value (both objects and primitive values) may be used as either a key or a value. Have a look at this piece of code:

A WeakMap is a Map in which the keys are weakly referenced, that doesn’t prevent its keys from being garbage-collected. That means you don’t have to worry about memory leaks.

A WeakMap only has four methods delete(key), , get(key) and set(key, value).

  1. w.set('a', 'b');
  2. // Uncaught TypeError: Invalid value used as weak map key
  3. const o1 = {},
  4. w.set(o1, 37);
  5. w.set(o2, "azerty");
  6. w.get(o3); // undefined, because that is the set value
  7. w.has(o1); // true
  8. w.has(o1); // false