11. Map and WeakMap

ES6 introduces new set of data structures called Map and WeakMap. Now, we actually use maps in JavaScript all the time. In fact every object can be considered as a Map.

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:

  1. const myMap = new Map();
  2. const keyString = "a string",
  3. keyObj = {},
  4. keyFunc = () => {};
  5. // setting the values
  6. myMap.set(keyString, "value associated with 'a string'");
  7. myMap.set(keyObj, "value associated with keyObj");
  8. myMap.set(keyFunc, "value associated with keyFunc");
  9. myMap.size; // 3
  10. // getting the values
  11. myMap.get(keyString); // "value associated with 'a string'"
  12. myMap.get(keyObj); // "value associated with keyObj"
  13. myMap.get(keyFunc); // "value associated with keyFunc"

WeakMap

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.

Another thing to note here- in WeakMap as opposed to Map every key must be an object.

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

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