WeakMap & WeakSet
Overview
In JavaScript, Memory Management is handled automatically by the 'Garbage Collector'. If you store an object inside a standard Map, Array, or Set, that object cannot be deleted from memory (even if it's no longer needed elsewhere) because the Map holds a 'Strong Reference' to it.
WeakMap and WeakSet fix this. They hold 'Weak References' to objects. If there are no other references to the object in your application, the Garbage Collector will silently delete it from the WeakMap, preventing catastrophic Memory Leaks.
Syntax
// 1. Keys MUST be Objects (Primitive keys are not allowed!)
// 2. WeakMaps are NOT iterable (No forEach, no .size property)
const cache = new WeakMap();
let tempUser = { name: "Kartik" };
cache.set(tempUser, "Secret Data");
console.log(cache.has(tempUser)); // true
// Later in the app, we delete the original reference
tempUser = null;
// The Garbage Collector sees 'tempUser' is null.
// It automatically deletes the entry from the 'cache' WeakMap!
// Memory is freed automatically.Common Pitfalls
- Trying to use
.sizeor iterate over a WeakMap. Because the Garbage Collector runs randomly, the exact contents of a WeakMap are technically indeterminable at any given exact millisecond. Therefore, iterating and size checking are intentionally disabled by the language.
Interview Questions
They prevent Memory Leaks. They allow you to associate data with an object without forcing that object to stay alive in memory forever. Once the object is no longer used by the rest of the application, it is automatically garbage collected.
Real-World Example
Attaching custom third-party metadata to a specific DOM element (like a Chart graph). When the user navigates to a new page and the DOM element is destroyed, the WeakMap automatically clears the associated metadata, preventing the app from crashing due to memory bloat over time.
const domMetadata = new WeakMap();
domMetadata.set(document.getElementById('chart'), chartConfig);Check Your Knowledge
Test your understanding of WeakMap & WeakSet with these quick questions.