The most important difference is that WeakMap
does not prevent the keys from being garbage collected when there is no references to the keys.
On the other hand, Map
maintains the references to keys and values indefinitely. Once the keys and values are created, they will take the memory and will not be garbage collected even if there is no references to them.
This could leads to a memory leak issue.
Consider a simple code below where we map an unique id to particular person's information:
let id = { value: 1 };
const people = new Map();
people.set(id, { name: 'Foo', age: 20, address: 'Bar' });
id = null;
After removing the key object id
, it is still able to access its reference via the map keys:
people.keys().next().value;
Because of this difference, WeakMap
as its name implies holds the weak references to the keys.
It explains why its keys are not enumerable which is mentioned in the previous difference.