WeakMap & WeakSet for Memory Management0%

WeakMap & WeakSet for Memory Management

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

WeakMap & WeakSet for Memory Management

In JavaScript, standard Map and Set collections hold strong references to their entries. If an object is placed inside a Map, the garbage collector cannot reclaim it, even if all other references to it have been destroyed. WeakMap and WeakSet hold weak references, allowing objects to be garbage-collected cleanly and preventing memory leaks.


1. Strong References vs. Weak References

Output
Standard Map (Strong Reference):
[ DOM Button ] ◄─── Held strongly by Map key!
▲
btn = null; <── Button is NOT collected because Map holds it alive! (Memory Leak!)
 
WeakMap (Weak Reference):
[ DOM Button ] < - - Weak Reference from WeakMap
▲
btn = null; <── Button IS GARBAGE COLLECTED! Key/value vanishes automatically!

2. Key Restrictions of Weak Collections

Because the garbage collector can reclaim keys at any moment:

  1. 1
    Keys MUST be Objects: Primitives (string, number) are not allowed as keys.
  2. 2
    Not Iterable: There is no .forEach(), for...of, .keys(), .values(), or .size property!
  3. 3
    No Clearing: There is no .clear() method.

Supported methods: .get(), .set(), .has(), .delete().


3. Top Production Use Cases

1. Attaching Private Metadata to DOM Elements

When tracking widget state without polluting DOM dataset attributes or leaking memory when elements are removed:

JavaScript
// Safe DOM element metadata cache
const elementClickTracker = new WeakMap();
 
function registerClick(buttonEl) {
const currentCount = elementClickTracker.get(buttonEl) || 0;
elementClickTracker.set(buttonEl, currentCount + 1);
console.log(`Button clicked ${currentCount + 1} times.`);
}
 
// When buttonEl is removed from the DOM:
buttonEl.remove();
buttonEl = null;
// The button and its count are AUTOMATICALLY garbage-collected! Zero memory leak!

2. True Private Data in Classes (Pre-ES2022 Pattern)

JavaScript
const privateData = new WeakMap();
 
class SecureUser {
constructor(secret) {
// Store secret mapped weakly to 'this' instance
privateData.set(this, { secret });
}
 
getSecret() {
return privateData.get(this).secret;
}
}

4. WeakSet: Unique Object Tracking

WeakSet stores a collection of weakly held objects. It is ideal for tagging objects or tracking "visited" status in graph traversals without altering the objects:

JavaScript
const visitedNodes = new WeakSet();
 
function traverseGraph(node) {
if (visitedNodes.has(node)) {
console.log('Cycle detected or already processed:', node.id);
return;
}
 
visitedNodes.add(node);
node.children.forEach(child => traverseGraph(child));
}

Interactive Quiz

Practice Quiz

Question 1
What is the primary difference between a Map and a WeakMap?
Question 2
Why does a WeakMap NOT have a .size property or .forEach() method?
Question 3
What error occurs if you attempt to use a primitive string as a key in a WeakMap (e.g. weakMap.set('id', 42))?
Question 4
Why is WeakMap ideal for caching data associated with DOM nodes?
Question 5
What methods are supported on a WeakSet instance?
Next Lesson

Object.freeze, Object.seal & Immutability

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext