Map, Set, WeakMap & WeakSet — JavaScript interview guide
13 / 23Language EssentialsMedium priorityMedium 20 min
Map, Set, WeakMap & WeakSet
Map is a key-value store where keys can be anything. Set stores unique values. The Weak versions do not stop their keys from being garbage collected.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
Set drops duplicates, Map accepts any key
Execution phaseStep 1/8
script.js
▶const nums = [1, 2, 2, 3, 3];2const unique = [...new Set(nums)];34const visits = new Map();5const page = { url: "/home" };6visits.set(page, 1);7visits.set(page, visits.get(page) + 1);8console.log(unique, visits.get(page));
Call Stack
last in, first outMemory / Scope
Global
| nums | [1, 2, 2, 3, 3] |
Console
nothing printed yet
What happens:An array with duplicates.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
When to use which
Map over object: any key type, keeps insertion order, has .size, fast add/delete.
Set: remove duplicates, fast "has" checks.
WeakMap: attach private data to objects or DOM nodes without leaking memory. Keys must be objects; not iterable.
const unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]
const visits = new Map();
visits.set(userObj, 3);
const meta = new WeakMap();
meta.set(domNode, { clicks: 0 }); // freed when domNode is removedRemember this
- Map keys compare by reference for objects.
- WeakMap/WeakSet are not iterable.
- Set is great for O(1) lookups.
Interview questions
Why use WeakMap instead of Map for caching per DOM node?
WeakMap holds keys weakly, so when the node is removed and unreferenced, the entry is garbage collected automatically.
Practice
- Find the first repeated character in a string using a Set.