← JavaScript

Intermediate · 12 of 17 · 17 min read

Set, Map, WeakMap and WeakSet

The four keyed collections, what each one does that an object or array cannot, and when the weak versions are the right answer.

  • Set, Map & friends

Before ES2015 there was one keyed collection: the plain object, with string keys. Map and Set were added because objects and arrays are the wrong tool for two very common jobs — keying by something that is not a string, and testing membership quickly.

Set

A collection with no duplicates, in insertion order.

const s = new Set([1, 2, 2, 3]);

console.log(s.size);        // 3 — the duplicate never got in
console.log(s.has(2));      // true  — O(1)
s.add(4).add(4);            // add returns the set, so it chains
s.delete(1);
console.log([...s]);        // [2, 3, 4]
console.log(s.has('2'));    // false — SameValueZero, no coercion

for (const value of s) console.log(value); // 2 / 3 / 4
s.forEach((v) => console.log(v));          // the same
s.clear();
console.log(s.size);        // 0

The two things it is for:

// 1. Dedupe
const tags = ['js', 'css', 'js', 'html'];
console.log([...new Set(tags)]);          // ["js", "css", "html"]
console.log(Array.from(new Set(tags)));   // the same

// 2. Fast membership, especially inside a loop
const banned = new Set(['a', 'b']);
const names = ['a', 'c'];
console.log(names.filter((n) => !banned.has(n))); // ["c"]

The performance difference is the real argument. array.includes scans; set.has is a hash lookup:

const big = Array.from({ length: 100_000 }, (_, i) => i);
const asSet = new Set(big);

// Inside a loop over n items, `includes` is O(n·m) and `has` is O(n):
console.log(big.includes(99_999)); // true — had to walk ~100k elements
console.log(asSet.has(99_999));    // true — one lookup

Equality is SameValueZero: like === except NaN equals itself. So objects are compared by reference, which surprises people:

const s = new Set();
s.add({ id: 1 });
s.add({ id: 1 });
console.log(s.size); // 2 — two different objects

s.add(NaN).add(NaN);
console.log(s.has(NaN)); // true, and still only one NaN

Deduping objects therefore needs a key:

const people = [{ id: 1 }, { id: 2 }, { id: 1 }];
const unique = [...new Map(people.map((p) => [p.id, p])).values()];
console.log(unique.length); // 2

Set operations are a few lines, and newer runtimes have them built in (union, intersection, difference):

const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);

console.log([...a].filter((x) => b.has(x)));  // [2, 3] — intersection
console.log([...a].filter((x) => !b.has(x))); // [1]    — difference
console.log([...new Set([...a, ...b])]);      // [1, 2, 3, 4] — union

Map

A dictionary whose keys keep their type.

const m = new Map([
  ['a', 1],
  ['b', 2],
]);

console.log(m.get('a'));  // 1
console.log(m.get('zzz')); // undefined
console.log(m.has('b'));  // true
m.set('c', 3).set('a', 99); // set chains, and overwrites
m.delete('b');
console.log(m.size);      // 2
console.log([...m.keys()], [...m.values()]); // ["a", "c"] [99, 3]
console.log([...m.entries()]); // [["a", 99], ["c", 3]]

for (const [key, value] of m) console.log(key, value); // destructures directly

What it does that an object cannot

Plain object Map
Key types strings and symbols only anything, including objects
Size Object.keys(o).length m.size
Iteration order integer-like keys first, then insertion insertion, always
Inherited keys toString, constructor, … none
Iterable directly no yes
Frequent add/remove slower optimised for it
JSON JSON.stringify works becomes {}

Keys keeping their type is the headline:

const keyObject = { id: 1 };

const asObject = {};
asObject[keyObject] = 'value';
console.log(Object.keys(asObject)); // ["[object Object]"] — coerced to a string

const asMap = new Map();
asMap.set(keyObject, 'value');
console.log(asMap.get(keyObject));   // "value"
console.log(asMap.get({ id: 1 }));   // undefined — a different object
console.log(asMap.set(1, 'num').set('1', 'str').size); // 2 — 1 and "1" are distinct

And the absence of inherited keys, which is a real bug class in object-as-dictionary code:

const counts = {};
console.log(counts['toString']);         // a function — inherited, not your data
console.log('toString' in counts);       // true

const safeCounts = new Map();
console.log(safeCounts.has('toString')); // false — a Map holds only what you put in

Choosing between them

Use a plain object when the keys are fixed, known strings and the thing is a record — a config, a parsed API response, a component’s props. Use a Map when the keys are dynamic data, when they are not strings, or when you add and remove entries throughout the object’s life.

// A record: an object is right.
const config = { theme: 'dark', retries: 3 };

// A lookup built at runtime, keyed by id: a Map is right.
const byId = new Map();
for (const row of [{ id: 7, name: 'Ana' }]) byId.set(row.id, row);
console.log(byId.get(7).name); // "Ana"

Converting between the two:

const m = new Map([['a', 1], ['b', 2]]);

console.log(Object.fromEntries(m));        // { a: 1, b: 2 }
console.log(new Map(Object.entries({ a: 1 }))); // Map(1) { "a" => 1 }
console.log(JSON.stringify(m));            // "{}" — this is the JSON trap
console.log(JSON.stringify([...m]));       // '[["a",1],["b",2]]' — serialise the entries

WeakMap and WeakSet

A normal Map keeps its keys alive forever: the map holds a reference, so the garbage collector cannot reclaim the object even when the rest of your program has forgotten it. That is a leak.

let node = { id: 1 };
const strong = new Map();
strong.set(node, 'metadata');

node = null;              // the only other reference is gone
console.log(strong.size); // 1 — the object is still held, and unreachable for you

A WeakMap holds its keys weakly: when nothing else refers to the key, the entry goes away.

let node = { id: 1 };
const weak = new WeakMap();
weak.set(node, 'metadata');

console.log(weak.get(node)); // "metadata"
node = null;                 // the entry becomes collectable
// no size, no keys(), no iteration — by design

The restrictions follow from that: you cannot enumerate a WeakMap, and it has no size, because the contents can change whenever the collector runs. Keys must be objects (or symbols) — a primitive has no identity to be weakly held.

const weak = new WeakMap();
// weak.set('a string', 1); // TypeError: Invalid value used as weak map key
console.log(Object.keys(weak), weak.size); // [] undefined
Map WeakMap
Key types anything objects and symbols only
Keeps the key alive yes no
Iterable / size yes no
Methods get, set, has, delete, iteration get, set, has, delete

What they are actually for: attaching data to an object you do not own, without deciding when it dies.

// 1. Metadata for DOM nodes — the entry disappears when the node is removed.
const clickCounts = new WeakMap();
function onClick(element) {
  clickCounts.set(element, (clickCounts.get(element) ?? 0) + 1);
}

// 2. A per-object cache that cannot leak.
const expensive = new WeakMap();
function compute(obj) {
  if (!expensive.has(obj)) expensive.set(obj, Object.keys(obj).length);
  return expensive.get(obj);
}
const data = { a: 1, b: 2 };
console.log(compute(data), compute(data)); // 2 2 — second call cached

WeakSet is the same idea with no values — a mark you can put on objects:

const visited = new WeakSet();

function walk(node) {
  if (visited.has(node)) return 'already seen'; // cycle protection, no leak
  visited.add(node);
  return 'visiting';
}

const a = { name: 'a' };
console.log(walk(a), walk(a)); // visiting / already seen

Common mistakes

JSON.stringify on a Map or Set

Mistake. Sending a Map to an API, or storing one in localStorage. Why it fails. Neither has a toJSON, so both serialise as {} and the data is silently lost. What to do instead. JSON.stringify([...map]) or Object.fromEntries(map), and rebuild with new Map(parsed).

Reaching for a Set to dedupe objects

Mistake. [...new Set(arrayOfObjects)]. Why it fails. Objects are compared by reference, so two identical-looking objects are two members. What to do instead. Dedupe by a key through a Map, as above.

Using a Map where an object is clearer

Mistake. A Map for a fixed set of known string keys. Why it fails. Nothing breaks, but you lose destructuring, spread, JSON, and the ability to type the shape — in exchange for a feature you are not using. What to do instead. Map for dynamic or non-string keys; object for records.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

What can a Map do that a plain object cannot?

When is a Set the right choice over an array?

What is a WeakSet actually for?

Practise Set, Map & friends →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.