Arrays, collections and copying · mid
Map, Set, WeakMap and WeakSet
Use Map for key-value data with any key type, frequent adds and deletes, and guaranteed insertion order; Set for unique values; and WeakMap or WeakSet when the key is an object whose lifetime you do not control, because weak keys do not stop garbage collection.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Map vs object: keys of any type (objects, functions), a size property, iteration in insertion order, no clashes with prototype keys like 'constructor', and good performance for frequent add/delete. A plain object suits fixed records and JSON.
- Map and Set use SameValueZero: NaN equals NaN, +0 equals -0, and objects are compared by reference, so two different {} are two keys.
- Set keeps unique values. Dedupe with [...new Set(arr)]. ES2025 added union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom (Baseline 2024).
- WeakMap and WeakSet: keys must be objects (or non-registered symbols since ES2023). Keys are held weakly. They have no size, no iteration and no clear, because their contents depend on when garbage collection runs.
- WeakMap uses: private data per object, caching derived data per object, metadata per DOM node, the 'seen' table in a deep clone.
- Map.prototype.getOrInsert / getOrInsertComputed (ES2026, Baseline 2026) replace the 'if missing, create' pattern.
- JSON.stringify(map) gives '{}'. Convert with Object.fromEntries(map) or [...map].
The red pen
Common traps: mistake → fix
Mistake: WeakMap values are weak
Fix: the keys are weak; the value lives as long as its key does.
Mistake: Map is always faster than an object
Fix: it depends; Map wins for dynamic keys and frequent deletes.
Mistake: Set compares objects by content
Fix: by reference.
Easy to hard
Questions interviewers ask, easy to hard
- When would you use a Map instead of a plain object?
- How do Map and Set treat object keys and NaN?
- What makes WeakMap different, and why can't you iterate it?
- Where have you needed a WeakMap?
- Use the ES2025 Set methods to compute who is both an admin and online.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.