Since EcmaScript 6 we have new classes, which can facilitate working with collections. Map and WeakMap are just two of these classes.
All objects in JavaScript can be looked at as we do at Map() objects. An Object, in summary, consists of properties and values. We could think of them like of keys and values.
var obj = new Object();
obj.a = 1;
obj.b = 2;
obj[0] = 3;
console.log(obj['a']);
console.log(obj['b']);
console.log(obj[0]);
console.log(obj);
Output:
1
2
3
{0: 3, a: 1, b: 2}
The below more advanced example treats the whole object as a key.
var obj = new Object();
var objKey = ({id: 1});
obj[objKey] = 4;
console.log(obj[objKey]);
console.log(Object
.getOwnPropertyNames(obj));
Output:
4
['[object Object]']
Which seems a bit odd due to the ['[object Object]'] index.
As we can see a JavaScript object cannot be treated as a dictionary.
And this is the reason to use the classes Map and WeakMap. So, what makes the WeakMap class so weak?
Let's assume, that an object as a key in WeakMap exists. Later all references to this object in JavaScript disappear at some point. JavaScript engine will remove the references from WeakMap.
Meaning WeakMap does not remember this object strongly. When object are to be cleared, then these will be automatically removed from WeakMap. Keys in WeakMap are not permanent. It is one of the reasons why we don't perform iterations over keys of WeakMap and showing all the variables stored in WeakMap can prove cumbersome.
Below we have an example of an ordinary map. We create keys which are of object type and set their values. In the next step we try to get a specified value.
let user1 = {name: 'Cesar'};
let user2 = {name: 'Kate'};
let users = new Map();
users.set(user1, 'Designer');
users.set(user2, 'Developer');
console.log(users.get(user1));
Output: Designer