What are WeakMap and WeakSet in JavaScript
· Category: JavaScript
Short answer
WeakMap and WeakSet hold object references weakly, meaning they do not prevent garbage collection and are not enumerable.
Steps
- Use WeakMap for private data:
javascript const privateData = new WeakMap(); class User { constructor(name) { privateData.set(this, { name }); } getName() { return privateData.get(this).name; } } - Use WeakSet for tracking objects:
javascript const seen = new WeakSet(); function process(obj) { if (seen.has(obj)) return; seen.add(obj); // process }
Tips
- Keys must be objects; primitives are not allowed.
- Use WeakMap instead of Symbol properties when you want data hidden even from
getOwnPropertySymbols.
Common issues
- You cannot iterate over WeakMap or WeakSet because entries may disappear at any time.
- If the only reference to an object is inside a WeakMap, it will be garbage collected.