Middle+
What is the difference between Map and WeakMap?
sobes.tech AI
Answer from AI
Main differences between Map and WeakMap:
-
Keys:
- Map can use any values (primitives and objects) as keys.
- WeakMap only accepts objects as keys.
-
Garbage collection:
- In Map, keys and values are held with strong references, so objects are not removed from memory as long as there is a reference in Map.
- In WeakMap, keys are held with weak references, meaning if the object key is no longer used elsewhere, it can be garbage collected along with the associated value.
-
Iteration:
- Map supports iteration over its elements (methods like forEach, keys, values, etc.).
- WeakMap does not support iteration because keys can disappear at any moment.
-
Usage:
- Map is suitable when you need to store key-value pairs with any key types and want to iterate over them.
- WeakMap is useful for storing data related to objects without preventing their removal from memory (e.g., for private object data).
Example of using WeakMap to store private data:
const privateData = new WeakMap();
class User {
constructor(name) {
privateData.set(this, { name });
}
getName() {
return privateData.get(this).name;
}
}
Here, user data is not accessible from outside and is automatically removed when the User object is deleted.