What are WeakSet and WeakMap, and how do they differ from Set and Map?
sobes.tech AI
Answer from AI
WeakSet and WeakMap are special collections in JavaScript that are similar to Set and Map but with important differences related to memory management and garbage collection.
Main differences:
-
Weak references: WeakSet and WeakMap store objects with weak references. This means that if an object in WeakSet or used as a key in WeakMap is no longer used elsewhere, it can be automatically removed by the garbage collector.
-
Objects only: In WeakSet and WeakMap, only objects can be used as keys (or elements); primitives cannot.
-
No iteration methods: WeakSet and WeakMap do not have methods for iterating over their contents (like forEach, keys, values) because their contents can change asynchronously due to garbage collection.
-
Usage: WeakMap is often used to store private data associated with objects without the risk of memory leaks.
Example:
let wm = new WeakMap();
let obj = {};
wm.set(obj, 'data');
obj = null; // now the object can be removed by the garbage collector, and the data in WeakMap will also disappear
Unlike Map and Set, which hold strong references and prevent objects from being deleted, WeakMap and WeakSet allow the garbage collector to free memory if objects are no longer used elsewhere.