Lesson 23 of 80
Map and Set, but the keys don't keep their objects alive — built specifically so caches and metadata stores don't cause memory leaks.
10 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
An object is used as a key in a Map, then every other reference to it is set to null. Can the garbage collector reclaim it?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
A regular Map holds a strong reference to every key — as long as the Map exists, none of its keys can be garbage-collected, even if nothing else in your program points to them anymore. A WeakMap holds its keys weakly: if an object used as a key has no other references left, the garbage collector can reclaim it, and the WeakMap's entry silently disappears too.
let user = { name: "Ada" };
const strongCache = new Map();
strongCache.set(user, "metadata");
user = null;
// user's object is STILL alive — strongCache is holding a reference to it
let user2 = { name: "Grace" };
const weakCache = new WeakMap();
weakCache.set(user2, "metadata");
user2 = null;
// user2's object CAN now be garbage-collected — weakCache doesn't keep it alive
WeakSet is the same idea for a set of objects instead of key-value pairs.
A Map holds a STRONG reference to its keys — the object stays alive as long as the Map does.
WeakMap is the language's built-in answer to "I want to attach data to an object without accidentally causing a memory leak.".keys(), no .size, no for...of. This isn't a missing feature; it's deliberate, because the contents can change at any moment as the GC runs, so a stable list of entries can't be guaranteed to exist."Why would you use a WeakMap instead of a Map?" checks whether you understand reachability and garbage collection as a real mechanism, not just "it's like Map but weak" — the why is the actual answer.