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:
const myMap = new Map();
const keyString = "a string",
keyObj = {},
keyFunc = () => {};
// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");
myMap.size; // 3
// getting the values
myMap.get(keyString); // "value associated with 'a string'"
myMap.get(keyObj); // "value associated with keyObj"
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)
.
const w = new WeakMap();
w.set('a', 'b');
// Uncaught TypeError: Invalid value used as weak map key
const o1 = {},
o2 = () => {},
o3 = window;
w.set(o1, 37);
w.set(o2, "azerty");
w.set(o3, undefined);
w.get(o3); // undefined, because that is the set value
w.has(o1); // true
w.delete(o1);
w.has(o1); // false