🔴 HardClosures & Scope💻 Output Question

WeakMap with garbage collectible keys

💡

Hint

Map holds a STRONG reference to keys — prevents GC. WeakMap holds a WEAK reference — key can be collected. That's why WeakMap has no .size or iteration.

What does this output?

let obj = { data: 'sensitive' };
const weakMap = new WeakMap();
const strongMap = new Map();

weakMap.set(obj, 'weak-value');
strongMap.set(obj, 'strong-value');

console.log(weakMap.has(obj));
console.log(strongMap.has(obj));

// After obj is dereferenced:
obj = null;

// WeakMap may release the entry (GC timing non-deterministic)
console.log(strongMap.size);

Correct Output

true
true
1

Why this output?

Explanation: Before null: both have the entry. After obj = null: WeakMap no longer prevents GC of the original object — entry may vanish. Map holds a strong reference — keeps the entry and size = 1. (WeakMap size is always inaccessible.)

Key Insight: Map holds a STRONG reference to keys — prevents GC. WeakMap holds a WEAK reference — key can be collected. That's why WeakMap has no .size or iteration.

More Closures & Scope Output Questions

🟢 EasyClassic var in loop closure→🟢 Easylet in loop closure (fix)→🟡 MediumClosure counter→🟡 MediumIIFE closure→

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz