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)
.
w.set('a', 'b');
// Uncaught TypeError: Invalid value used as weak map key
const o1 = {},
w.set(o1, 37);
w.set(o2, "azerty");
w.get(o3); // undefined, because that is the set value
w.has(o1); // true
w.has(o1); // false