What are WeakMap and WeakSet used for in JavaScript?
Understand how WeakMap and WeakSet help with memory-safe key/value storage using weak references.
Question
What are WeakMap and WeakSet used for in JavaScript?
Answer
WeakMap and WeakSet store weak references to objects — meaning if there are no other references to that object, it can be garbage collected.
WeakMap→ key-value pairs where keys must be objectsWeakSet→ set of objects, no primitives
const wm = new WeakMap();
let obj = {};
wm.set(obj, 'private data');
obj = null; // object can now be garbage collected
This is useful for caching, storing metadata, or private data tied to object lifecycles.
Real-World Example
Libraries use WeakMap to store component metadata without risking memory leaks.
Quick Practice
Create a WeakMap and store a DOM element as a key with some data. Then remove the DOM element — explain what happens.
Summary
Use WeakMap/WeakSet when you want to associate data with objects without preventing garbage collection.
Why can’t I iterate over WeakMap or WeakSet?
Because their entries can disappear anytime due to garbage collection, so iteration is not reliable.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.