JavaScript · The language round
When should you use Set, Map, WeakSet and WeakMap?
Short answer
Set stores unique values and Map stores key-value pairs. WeakSet and WeakMap hold objects weakly, so their entries do not prevent garbage collection and cannot be iterated.
The weak collections are about memory ownership. If a cache or metadata table should not keep an object alive, a WeakMap or WeakSet lets the garbage collector reclaim the key when nothing else references it.
const seen = new Set();
seen.add("a");
seen.add("a");
console.log(seen.size); // 1
const metadata = new WeakMap();
const element = document.querySelector("#app");
metadata.set(element, { clicks: 0 });
console.log(metadata.get(element)); // { clicks: 0 }The differences
Setstores unique values of any type and is iterableWeakSetstores objects only, is not iterable, and has nosizeMapstores key-value pairs with any key type and is iterableWeakMapaccepts objects as keys, is not iterable, and has nosize- Weak collection entries disappear when the key is no longer reachable elsewhere
Weak collections are not enumerable because enumeration would expose the garbage collector's timing and make behaviour non-deterministic. You can only get, set, has and delete on a WeakMap; a WeakSet supports add, has and delete.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why can't you iterate a WeakMap?
- 2What types can be WeakMap keys?
- 3When would a Set be better than an array?
- 4How does a WeakMap help avoid memory leaks?
Say it in the interview
A Set stores unique values, and a Map stores key-value pairs. WeakSet and WeakMap hold objects weakly, so they do not keep keys alive and cannot be iterated. WeakMap is useful for attaching metadata to objects or caching without preventing garbage collection. If I need to enumerate entries or know the size, I use Map or Set instead.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.