Sub topic 17
Choosing the Right Collection
This chapter assumes you have worked through the earlier chapters on Map, Set, SameValueZero, iteration, conversion, and the weak collections. It also assumes you are comfortable with the difference between primitive values and object references. The goal here is to pull that material together into a repeatable way of picking a data structure, and to show the mistakes that come from picking the wrong one.
The Questions That Decide It
Most choices come down to five questions. Ask them in this order:
- Do you need key-value pairs, or only membership? Membership means "is this thing in the group?" with no data attached. That points to a
SetorWeakSet. Pairs point to an object,Map, orWeakMap. - What are the keys? Plain objects coerce every key to a string or symbol. If your keys are objects, numbers you want kept as numbers, or arbitrary user input, prefer a
Map. - Should the collection keep its keys alive? If an entry describes an object owned by someone else and should disappear when that object does, you want a weak collection.
- Do you need size, iteration, or clearing? Weak collections offer none of these. If you need any of them, you need a strong collection.
- Must the data cross a JSON boundary often? Plain objects and arrays serialize directly. A
MaporSetneeds a conversion step every time.
Side-by-Side Comparison
| Feature | Array | Plain object | Map | Set | WeakMap | WeakSet |
|---|---|---|---|---|---|---|
| Stores | Ordered values | String/symbol keyed values | Any key, any value | Unique values | Object/symbol key, any value | Unique objects/symbols |
| Key equality | Index | String coercion | SameValueZero | SameValueZero | Identity | Identity |
| Order | Index order | Integer keys first, then insertion | Insertion | Insertion | None exposed | None exposed |
| Size | `length` | `Object.keys(o).length` | `size` | `size` | Not available | Not available |
| Iterable | Yes | Via `Object.entries` | Yes | Yes | No | No |
| Membership check cost | O(n) with `includes` | Fast | Fast | Fast | Fast | Fast |
| JSON-ready | Yes | Yes | No, convert entries | No, spread to array | No | No |
| Keeps keys alive | Yes | Yes | Yes | Yes | No | No |
| Inherited keys risk | No | Yes, unless `Object.create(null)` | No | No | No | No |
Two rows explain most bad choices. "Membership check cost" is why array.includes inside a loop gets slow on large inputs. "Keeps keys alive" is why a Map used as an object cache can leak memory.
Common Mistakes and Their Fixes
Using an object as a dictionary for arbitrary keys
A plain object inherits from Object.prototype, so some keys are already "present" before you add anything. Counting words with an object shows the problem:
const words = ['hello', 'constructor', 'hello'];
const asObject = {};
for (const w of words) {
asObject[w] = (asObject[w] || 0) + 1;
}
console.log(typeof asObject.constructor); // 'string' (Object function + 1)
const asMap = new Map();
for (const w of words) {
asMap.set(w, (asMap.get(w) ?? 0) + 1);
}
console.log(asMap.get('constructor')); // 1
console.log(asMap.get('hello')); // 2asObject.constructor started out as the inherited Object function, which is truthy, so the code concatenated 1 onto it. The Map version has no inherited entries. Object.create(null) also fixes this for objects. Even with that fix, you still don't get size or direct iteration, and you still get string coercion of keys.
Expecting structural equality from Map keys
SameValueZero compares objects by reference. Two arrays with the same contents are different keys:
const grid = new Map();
grid.set([1, 2], 'tree');
console.log(grid.get([1, 2])); // undefined
const key = (x, y) => `${x},${y}`;
grid.set(key(1, 2), 'tree');
console.log(grid.get(key(1, 2))); // 'tree'When the logical key is made of several primitives, build a string key, or nest Maps (Map<x, Map<y, value>>). Use nested Maps when the parts can't be joined into a string without ambiguity.
Caching object results in a strong Map
const strongCache = new Map();
const weakCache = new WeakMap();
function measure(node, cache) {
if (!cache.has(node)) {
cache.set(node, JSON.stringify(node).length);
}
return cache.get(node);
}
let node = { id: 1, label: 'temporary' };
console.log(measure(node, strongCache)); // 28
console.log(measure(node, weakCache)); // 28
node = null;
console.log(strongCache.size); // 1: the object is still reachableAfter node = null, the strong cache still holds the object, so it can never be collected. The weak cache doesn't keep it alive, and the engine can drop that entry whenever garbage collection runs. Use a Map cache only when you also have an eviction policy, such as a size limit or a time limit. Otherwise use a WeakMap.
Reaching for a weak collection when you need to list entries
If you need to report "all active sessions" or count them, a WeakMap can't do it, because its contents depend on garbage collection timing. Use a Map and delete entries explicitly when sessions end. You can also combine both: a Map for the registry you list, and a WeakMap for per-object data that should not outlive the object.
Worked Example: One Feature, Four Collections
A small notification system shows how each collection fits a different job:
class Notifier {
#subscribers = new Set(); // unique listeners, iterated on publish
#countsByTopic = new Map(); // arbitrary string keys, needs size and listing
#lastSeen = new WeakMap(); // per-listener data, dies with the listener
#muted = new WeakSet(); // a flag on listeners, no extra data
subscribe(fn) { this.#subscribers.add(fn); }
mute(fn) { this.#muted.add(fn); }
publish(topic, payload) {
this.#countsByTopic.set(topic, (this.#countsByTopic.get(topic) ?? 0) + 1);
for (const fn of this.#subscribers) {
if (this.#muted.has(fn)) continue;
this.#lastSeen.set(fn, topic);
fn(topic, payload);
}
}
lastTopicFor(fn) { return this.#lastSeen.get(fn); }
stats() { return Object.fromEntries(this.#countsByTopic); }
}
const n = new Notifier();
const log = (t, p) => console.log(`[${t}]`, p);
const quiet = () => console.log('should not run');
n.subscribe(log);
n.subscribe(log); // ignored: Set keeps one copy
n.subscribe(quiet);
n.mute(quiet);
n.publish('build', 'ok'); // [build] ok
n.publish('deploy', 'ok'); // [deploy] ok
console.log(n.lastTopicFor(log)); // 'deploy'
console.log(n.stats()); // { build: 1, deploy: 1 }Each choice follows from the questions above:
- Subscribers need uniqueness and iteration, so they go in a
Set. - Topic counts have string keys, need listing, and must be exported as JSON-friendly data, so they go in a
Map, converted at the edge withObject.fromEntries. - "Last topic seen" is data about a listener and should not outlive it, so it goes in a
WeakMap. - "Muted" is a yes/no flag about a listener, so it goes in a
WeakSet.
The Set of subscribers still holds listeners strongly. That's correct here, because subscribing is meant to keep a listener active until it unsubscribes.
Quick Rules of Thumb
- Fixed record shape, sent as JSON: plain object.
- Dynamic dictionary, any key type, frequent adds and deletes:
Map. - Uniqueness, fast membership, set algebra:
Set. - Data about objects you don't own:
WeakMap. - Flags about objects you don't own:
WeakSet. - Ordered list with duplicates or index access: array.
Exercise
You are tracking which DOM elements a library has already initialized so it doesn't initialize them twice. Elements may be removed from the page at any time. Which collection fits, and why not a Set?
Show answer
A WeakSet. You only need a yes/no membership flag on objects you don't own. A Set would hold removed elements strongly and keep them in memory, while a WeakSet lets them be collected once the page drops them.
Exercise
An API returns user preferences as JSON, your code reads a few known fields, and you send the object back unchanged. Should you convert it to a Map?
Show answer
No. The shape is fixed and known, keys are strings, and the data crosses a JSON boundary in both directions. A plain object avoids two conversion steps and serializes directly.
Exercise
A function caches results keyed by a pair of numbers (row, column) using cache.set([row, col], value). Lookups always miss. Explain the cause and give two fixes.
Show answer
Map compares array keys by reference under SameValueZero, so each new [row, col] array is a different key. Fix it with a string key such as ${row},${col}, or with nested Maps, where the outer Map is keyed by row and holds an inner Map keyed by column.
Exercise
A team needs to show an admin page listing every open connection, and also to attach a per-connection buffer that should be released when the connection object is gone. Which collections would you use?
Show answer
A Map (or Set) for the registry of open connections, because the admin page needs iteration and size, with entries deleted explicitly on close. A WeakMap for the per-connection buffers, so they are released with the connection object and don't depend on manual cleanup.