Sub topic 1
Why JavaScript Has Keyed Collections
JavaScript programs constantly need to answer two kinds of question. One is "what value goes with this key?" The other is "have I seen this value before?" For most of the language's history, developers used plain objects for the first and arrays for the second. Both work for simple cases. Both also break in ways that are easy to miss until a bug appears in production.
ES2015 added four built-in keyed collections: Map, Set, WeakMap, and WeakSet. A keyed collection stores entries that you look up by a key rather than by a numeric position. This chapter explains what problems these collections solve and how the four relate to each other. Later chapters cover each one in detail.
Prerequisites
This chapter and the rest of the tutorial assume you are comfortable with:
- JavaScript variables, functions, and arrow functions
- Objects and arrays, including property access with dot and bracket notation
for...ofloops and the spread operator (...)- Basic ES classes
- The difference between primitive values (strings, numbers, booleans,
null,undefined, symbols, bigints) and object references
If any of these feel unfamiliar, review them first. The behavior of weak collections in particular depends on understanding that two variables can refer to the same object.
The Problem with Objects as Dictionaries
A plain object maps property names to values, so it looks like a natural dictionary. It carries three design decisions that get in the way when you use it for arbitrary data.
Object keys become strings
Object property keys can only be strings or symbols. Any other value you use as a key gets converted to a string. Objects convert to "[object Object]", so different objects collide on the same key:
const alice = { id: 1 };
const bob = { id: 2 };
const lookup = {};
lookup[alice] = 'first';
lookup[bob] = 'second';
console.log(lookup[alice]); // 'second'
console.log(Object.keys(lookup)); // ['[object Object]']Numbers get converted too. lookup[1] and lookup['1'] refer to the same property. You cannot use an object, a function, or a DOM element as a key and expect to get it back.
Objects inherit keys you did not add
A literal like {} inherits from Object.prototype. Names such as constructor, toString, and hasOwnProperty already resolve to something. A word counter built on an object shows the problem:
function countWords(words) {
const counts = {};
for (const word of words) {
counts[word] = (counts[word] || 0) + 1;
}
return counts;
}
const result = countWords(['map', 'set', 'constructor', 'map']);
console.log(result.map); // 2
console.log(typeof result.constructor); // 'string'
console.log(result.constructor.slice(0, 17)); // 'function Object()'When the word is constructor, counts[word] finds the inherited Object function. function + 1 turns into string concatenation, which corrupts the result. You can avoid this with Object.create(null) or with Object.hasOwn checks. Both work, but you have to remember to use them every time.
Objects have no direct size or guaranteed purpose
An object has no size property. You compute the count with Object.keys(obj).length, which builds a whole array just to measure it. Iteration order also follows special rules: integer-like keys come first in ascending order, then string keys in insertion order. Engines also optimize objects for a fixed shape that you set up once and read often. They are tuned less for heavy adding and removing of keys.
The Problem with Arrays as Sets
To track unique values with an array, you check before you push:
const seen = [];
function remember(value) {
if (!seen.includes(value)) {
seen.push(value);
}
}
remember('a');
remember('b');
remember('a');
console.log(seen); // ['a', 'b']This is correct, but includes scans the array from the start on every call. With n stored values, each check costs O(n), so adding n items costs O(n²). Removing a value requires indexOf followed by splice, which is also linear. An array also says nothing about intent: a reader can't tell from the type that duplicates are forbidden.
What the Keyed Collections Provide
Each keyed collection fixes one of these problems directly.
| Collection | Stores | Key types | Iterable | Has `size` | Holds keys strongly |
|---|---|---|---|---|---|
| `Map` | key → value pairs | Any value | Yes, insertion order | Yes | Yes |
| `Set` | unique values | Any value | Yes, insertion order | Yes | Yes |
| `WeakMap` | key → value pairs | Objects and non-registered symbols | No | No | No |
| `WeakSet` | unique values | Objects and non-registered symbols | No | No | No |
Here is the first broken example rewritten with a Map. Keys keep their identity, and nothing is inherited:
const alice = { id: 1 };
const bob = { id: 2 };
const lookup = new Map();
lookup.set(alice, 'first');
lookup.set(bob, 'second');
console.log(lookup.get(alice)); // 'first'
console.log(lookup.size); // 2
console.log(lookup.has('constructor')); // falseAnd the uniqueness tracker with a Set:
const seen = new Set();
seen.add('a').add('b').add('a');
console.log(seen.size); // 2
console.log(seen.has('a')); // trueThe specification requires Map and Set lookups to run in sublinear time on average. In practice engines use hash tables, so has, get, add, and delete take roughly constant time no matter how many entries you store.
The strong and weak families
The four collections form two pairs. Map and Set hold their contents strongly: as long as the collection is reachable, every key and value in it stays in memory. WeakMap and WeakSet hold their keys weakly. If nothing else in the program refers to a key object, the garbage collector may reclaim it, and its entry disappears.
Weak holding costs you features. The garbage collector decides when an entry vanishes, so its contents are nondeterministic. A weak collection therefore can't report a size or let you loop over its entries. You can only ask about a key you already hold. This trade-off makes weak collections a good fit for caches and per-object metadata that should not keep objects alive.
Common Misconceptions
- "Map replaces objects." It doesn't. Objects are still the right tool for records with a known, fixed set of fields, and for data you send as JSON.
Mapfits dictionaries whose keys come from runtime data. - "Set compares objects by content." It compares objects by reference. Two separate
{ id: 1 }literals are two different entries. A later chapter covers the exact equality rule, called SameValueZero. - "Weak means the entry is removed as soon as I stop using it." Collection happens whenever the engine decides to run it, which may be much later or, for a short-lived program, never.
- "Bracket access works on a Map."
map['x'] = 1sets an ordinary property on the Map object. It doesn't add an entry, somap.get('x')returnsundefined.
What Comes Next
The following chapters take each collection in turn. They cover the Map and Set APIs and the SameValueZero equality rule, then iteration, conversion, and grouping. After that come reachability, the weak collections, and how to choose among them.
Exercise
A program stores a click count for each DOM button using counts[button] = (counts[button] || 0) + 1, where counts is a plain object. After clicking three different buttons once each, Object.keys(counts) has length 1 and the stored value is 3. Explain why, and name the collection that fixes it.
Show answer
Object keys must be strings or symbols, so each button object is converted to a string such as "[object HTMLButtonElement]". All three buttons map to the same key, and their counts accumulate in one entry. A Map keyed by the button objects keeps each one separate. A WeakMap also works, and it avoids keeping removed buttons in memory.
Exercise
Why can't a WeakSet offer a size property or a for...of loop, when a Set can?
Show answer
A WeakSet holds its objects weakly, so the garbage collector may remove entries at any time once nothing else refers to them. The number of entries and the result of iterating would depend on when collection happens to run. That would make the results unpredictable, so the API exposes only operations on objects you already hold: add, has, and delete.