Map, Set and Weak Collections
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Choose between a plain object, a Map and a Set for a given task.
- Use Map and Set iteration and size without converting to arrays.
- Explain how WeakMap and WeakSet enable garbage collection.
Overview
#Map versus object
A Map keeps insertion order, allows any value as a key, and exposes size and direct iteration. A plain object coerces keys to strings or symbols and has no reliable size. Use a Map when keys are dynamic or not strings, and an object when the shape is fixed and you benefit from literal syntax.
const counts = new Map();
counts.set('a', 1);
counts.set({ id: 1 }, 2);
console.log(counts.size, counts.get('a')); // 2 1
Set for uniqueness
A Set stores unique values using the same equality as Object.is, so NaN is a single entry and objects are compared by reference. It removes duplicates in one pass and answers membership in constant time.
console.log([...new Set([1, 1, 2, NaN, NaN])]); // [1, 2, NaN]
Weak collections
WeakMap and WeakSet hold weak references to their keys. If nothing else references a key, the entry disappears and the memory can be reclaimed. They are not iterable and have no size, which is exactly what makes them safe for attaching metadata to objects without leaking them.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this line print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconst s = new Set([1, 1, NaN, NaN]); const m = new Map([[{}, 1], [{}, 2]]); console.log(s.size, m.size);Exercise 2Explain
Explain when a Map is a better choice than a plain object.
starter.textconst m = new Map(); m.set(1, 'one');Reveal the reference answer
reference.textA Map allows keys of any type, including numbers, objects and functions, without coercion, and it keeps insertion order and exposes size. A plain object turns every key into a string or symbol, which can collide, and it has prototype keys that can interfere with lookups. I use a Map for dynamic keys, frequent add and delete, and iteration, and an object for fixed records written as literals.Authored expected output: one
The answer should name key typing, coercion, order, size and prototype interference as the deciding factors.
Exercise 3Implement
Implement `uniqueBy(items, keyOf)` so it returns the first item for each distinct key. Running `console.log(uniqueBy([{ id: 1 }, { id: 1 }, { id: 2 }], (x) => x.id).length)` should print `2`.
starter.javascriptfunction uniqueBy(items, keyOf) { // your code here }Reveal the reference answer
reference.javascriptfunction uniqueBy(items, keyOf) { const seen = new Set(); const out = []; for (const item of items) { const key = keyOf(item); if (!seen.has(key)) { seen.add(key); out.push(item); } } return out; }Authored expected output: 2
A Set records which keys have been seen. The first item for each key is kept and later duplicates are skipped, which preserves order and runs in one pass.
Exercise 4Debug
This cache is meant to key by object identity but returns the wrong value for different objects. Find and fix the bug.
starter.javascriptconst cache = {}; function remember(key, value) { cache[key] = value; } remember({ id: 1 }, 'a'); remember({ id: 1 }, 'b'); console.log(Object.keys(cache).length);Reveal the reference answer
reference.javascriptconst cache = new Map(); function remember(key, value) { cache.set(key, value); } remember({ id: 1 }, 'a'); remember({ id: 1 }, 'b'); console.log(cache.size);Authored expected output: 2
Using an object as a property key coerces it to the string '[object Object]', so both calls overwrite one entry. A Map keeps the object references distinct, so there are two entries.
Exercise 5Test
Write assertions that prove Set deduplicates by value and that Map preserves insertion order.
starter.javascriptfunction assertEqual(actual, expected, label) { if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(label + ': unexpected value'); }Reveal the reference answer
reference.javascriptassertEqual([...new Set([3, 1, 3, 2])], [3, 1, 2], 'Set keeps first-seen order'); const m = new Map(); m.set('b', 2); m.set('a', 1); assertEqual([...m.keys()], ['b', 'a'], 'Map keeps insertion order'); assertEqual(m.size, 2, 'Map size counts entries'); console.log('all assertions passed');Authored expected output: all assertions passed
Set stores values in first-seen order and drops later duplicates. Map iterates keys in the order they were set, unlike an object where integer-like keys are reordered.
Exercise 6Interview
How would you attach metadata to DOM nodes without leaking memory?
Reveal the reference answer
reference.textI use a WeakMap keyed by the node. When the node is removed and nothing else references it, the entry and its value become collectable, so I do not have to clean up manually. I avoid adding expando properties to the node itself, and I avoid a plain Map, which would keep the node alive forever.The answer should connect weak keys to garbage collection and contrast with a strong Map that would retain the node.
Common misconceptions
#- A Map can be serialized to JSON directly.
- Set stores duplicates and removes them on read.
- WeakMap can be iterated to list its entries.
Follow-up practice
#- javascript-foundations-symbols-and-well-known-symbols
- javascript-foundations-metaprogramming
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.