Curriculum
Concept 63 // Module 07: Collections, Iteration & Modules
WeakMap, WeakSet & Weak References
Module 07: Collections, Iteration & Modules•Concept 63 of 100• 5 min read
WeakMap, WeakSet & Weak References
`WeakMap` and `WeakSet` are collections whose keys (for WeakMap) and values (for WeakSet) must be objects (or non-registered symbols) and are held **weakly**. If no other reference to the object exists, it can be garbage collected.
The Core Concept
Because keys are weak and can disappear at any moment during garbage collection, `WeakMap` and `WeakSet` are **not iterable** and have no `.size` property or `.keys()` method.
Syntax Reference
const wm = new WeakMap();
let key = { id: 1 };
wm.set(key, "metadata");
key = null; // The entry is automatically removed from memory by GC!Live Interactive Studio
Because the reference is weak, WeakMap prevents memory leaks when DOM elements are created and removed dynamically.
JavaScript Editor
Loading...
Console Output
Waiting for output...
Key Code Patterns in Action
01
Storing Private DOM Node Metadata
const clickCounters = new WeakMap();
function trackClick(btnElement) {
let count = clickCounters.get(btnElement) || 0;
clickCounters.set(btnElement, count + 1);
console.log("Button clicked:", count + 1);
}
// When btnElement is removed from the DOM and discarded,
// its counter in WeakMap is automatically garbage-collected!Because the reference is weak, WeakMap prevents memory leaks when DOM elements are created and removed dynamically.
02
WeakSet for Object Tagging
const visitedNodes = new WeakSet();
function processNode(node) {
if (visitedNodes.has(node)) {
return; // Already processed
}
visitedNodes.add(node);
console.log("Processing unique node:", node.id);
}
let item = { id: 42 };
processNode(item);
processNode(item); // SkippedWeakSet lets you tag objects with booleans without modifying the objects or preventing their garbage collection.
03
1. Core Usage: WeakMap, WeakSet & Weak References
// Core syntax and usage for WeakMap, WeakSet & Weak References
const feature = 'weakmap-weakset-weak-references';
console.log('Concept 63:', feature);
console.log('Active:', true);Illustrates the fundamental invocation and syntax structure for WeakMap, WeakSet & Weak References.
04
2. Defensive Handling & Edge Case
// Edge-case defensive handling
function handleSafe(input) {
if (input === null || input === undefined) return 'safe-fallback';
return String(input).trim();
}
console.log(handleSafe('weakmap-weakset-weak-references'));
console.log(handleSafe(null));Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with WeakMap, WeakSet & Weak References.
05
3. Clean Architecture & Production Pattern
// Production-grade pattern for WeakMap, WeakSet & Weak References
const settings = Object.freeze({
id: 'weakmap-weakset-weak-references',
ready: true,
timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);Demonstrates clean, immutable production code avoiding unintended state mutations.
Real-World Engineering Takeaways
Preventing Memory Leaks: Associating temporary metadata with external DOM elements.
Truly Private Class State: Emulating private instance variables in ES5 libraries.
Memoization Caches: Caching computed results for objects without pinning them in memory.
Under the Hood: Engine & Memory Mechanics
How JavaScript Executes This
V8 Ephemeron tables link keys weakly. The garbage collector does not treat WeakMap keys as GC roots; if no strong path exists to the key, the key and its value are swept during Mark-Sweep.
Quick Knowledge Check
Test your understanding on these 10 questions (one by one):
Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model
What is the core purpose of WeakMap, WeakSet & Weak References in JavaScript?
// Concept 63: WeakMap, WeakSet & Weak References
// Understanding the core mental model1 / 10