Curriculum
Module 33 // Core JavaScript
Map, Set, WeakMap, WeakSet
Module Objective
Key equality, weak references, garbage collection behavior
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Removing Duplicates
const raw = [1, 5, 2, 1, 5, 3];
const unique = [...new Set(raw)];
console.log(unique); // [1, 5, 2, 3]💡 Converting an array to a `Set` and back to an array is the fastest way to remove duplicates in modern JavaScript.
// Example 2
// 2. Objects as Map Keys
const user = { name: "Subhajit" };
const metadata = new Map();
metadata.set(user, { lastLogin: "2025-12-17" });
console.log(metadata.get(user)); // { lastLogin: ... }💡 In a regular Object, keys are converted to strings. A `Map` allows you to use actual objects as keys, which is powerful for associating metadata without modifying the original object.
// Example 3
// 3. WeakMap for Private Data
const privates = new WeakMap();
class User {
constructor(id) {
privates.set(this, { id });
}
getId() {
return privates.get(this).id;
}
}
const me = new User(42);
console.log(me.getId()); // 42💡 `WeakMap` doesn't prevent its keys from being **Garbage Collected**. If the `User` instance is deleted, the private data in the `WeakMap` is automatically removed from memory.
Engine & Memory Architecture
Hash Table Internals
1. Hash Maps:
MapandSetuse Hash Tables in the Heap for O(1) average time complexity for access.- Standard Objects also use hash tables, but
Mapis optimized for frequent additions/removals.
2. Garbage Collection (Weak Variants):
- Strong Reference: A standard
Mapkeeps its keys alive in the RAM as long as the map exists. - Weak Reference: A
WeakMapholds a "weak" reference. If no other code points to the key object, the Garbage Collector can reclaim that memory even if it's still in the map.
3. Memory Overhead:
- Each
Mapentry requires more memory than a standard Object property due to the complexity of the Hash Table structure.