QA
Intermediate LevelJavaScript & TypeScript

How do WeakMap, WeakSet, and WeakRef prevent memory leaks?

❓ Interview Prompt: Compare WeakMap and WeakSet against Map and Set regarding garbage collection and object reference retention.

In a standard Map or Set, stored object keys/values are held with a strong reference, preventing the garbage collector from freeing them even if all other references in the app are deleted.

WeakMap & WeakSet:

•
Hold weak references to object keys.
•
Keys must be objects (or non-registered Symbols), never primitives.
•
If there are no other references to a key object outside the WeakMap/WeakSet, the object is automatically garbage collected and removed from the collection.
•
Not iterable (no .keys(), .values(), or forEach) because GC timing is non-deterministic.

Code Implementation Example

typescript
// Zero memory leak cache with WeakMap
const privateMetadata = new WeakMap<object, { lastAccessed: number }>();

function trackAccess(obj: object) {
  privateMetadata.set(obj, { lastAccessed: Date.now() });
}

let user: { name: string } | null = { name: 'Alice' };
trackAccess(user);

// When user is set to null, memory is reclaimed automatically by GC!
user = null;
💡Attaching private object metadata with WeakMap without memory leaks.
🎯 Interview Key Takeaway

Use WeakMap to attach metadata to objects without preventing garbage collection.

#WeakMap#Memory Leaks#Garbage Collection#Intermediate
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?