Map, Set, and Weak Collections
Why `Map` and `Set` exist alongside objects and arrays, when they're the better tool, and how `WeakMap`/`WeakSet` avoid leaks with weak references.
Map, Set, and Weak Collections
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A plain object's keys are coerced to strings, so using a non-string value (an object, a number you care about staying a number) as a key silently breaks; `Map` keys can be *any* value, compared by identity, with no coercion.
- `Map` tracks insertion order and exposes a real `.size`, where a plain object has no guaranteed key order before ES2015 conventions and no built-in count — you'd have to call `Object.keys(obj).length` every time.
- `Set` stores unique values with no keys at all — its whole job is "a collection with no duplicates," which is cheaper and clearer than faking that with an array and manually checking `includes` before every insert.
- `WeakMap` and `WeakSet` hold their entries with *weak references* — if nothing else in the program still references a key/value, the garbage collector is free to reclaim it, even though the `WeakMap` still technically holds it.
- That weak-reference behavior is the entire reason `WeakMap`/`WeakSet` exist: attaching extra data to an object (metadata, a cache, private state) without that attachment being the thing that keeps the object alive forever and leaks memory.
Why not just use objects and arrays for everything
Objects and arrays cover a huge amount of ground, which is exactly why it’s
easy to miss where they quietly fall short. A plain object forces every key
through a string coercion — pass it an object, a Date, anything that
isn’t already a string or symbol, and it gets stringified before it’s used
as a key. Two different objects can collide onto the identical key without
any error, because they both stringify to the same thing. An array can
hold unique values, but only if you remember to check for duplicates
before every insert — the array itself has no opinion about uniqueness.
Map and Set exist because “key/value pairs” and “a collection with no
duplicates” are common enough problems to deserve purpose-built data
structures, rather than objects and arrays pressed into service and
patched around their gaps.
Map: a key/value collection that doesn’t fight you
A Map is conceptually the same idea as a plain object — keys and values —
with three concrete advantages that come straight from being designed for
the job:
const cache = new Map();
const key = { id: 1 }; // a real object as a key — fine for a Map, broken for a plain object
cache.set(key, "cached result");
cache.get(key); // "cached result" — looked up by identity, no coercion
cache.size; // 1 — no need to call Object.keys(...).length
Any value can be a key, compared by identity rather than coerced to a
string. Insertion order is preserved when you iterate. And .size is just
there, maintained automatically — no derived count, no risk of it getting
stale. The embedded video walks through this same contrast directly against
plain objects and arrays, which is worth watching specifically for the
side-by-side: seeing why each Map feature exists, next to the object
behavior it’s fixing, lands better than a feature list on its own.
Set: uniqueness as the whole point
Set strips away the key/value pairing entirely and keeps just one
guarantee: every value it holds is unique. Adding a value that’s already
present is a no-op — there’s no error, it just doesn’t duplicate.
const tags = new Set(["js", "web"]);
tags.add("js"); // no-op, "js" is already in the set
tags.size; // 2
Compare that to the array equivalent, where you’d have to write
if (!tags.includes("js")) tags.push("js") every single time you insert —
Set makes “no duplicates” the default instead of something you enforce
by convention.
WeakMap and WeakSet: not holding on too tight
WeakMap and WeakSet look like restricted versions of Map and Set —
you can’t iterate them, there’s no .size, and WeakMap keys (and
WeakSet values) have to be objects, never primitives. Those restrictions
exist to support one specific, important property: weak references.
A regular Map holds a strong reference to everything you put in it —
as long as the Map is alive, every key and value it holds is kept alive
too, whether or not anything else in your program still cares about them.
That’s exactly the shape of a memory leak: attach data to an object in a
long-lived Map, forget to clean it up when the object is done, and that
object (plus whatever you attached) sits in memory forever.
const metadata = new WeakMap();
function attachMetadata(domElement, data) {
metadata.set(domElement, data);
}
If domElement is later removed from the page and nothing else in the
program references it, the garbage collector is free to reclaim it — and
its entry in metadata — automatically, because WeakMap never counted
as a reason to keep it alive. That’s the entire reason weak collections
exist: attaching extra data (a cache entry, private state, some metadata)
to an object without that attachment itself becoming a memory leak. It’s
also exactly why you can’t iterate a WeakMap or ask its size — entries
can vanish at any moment the garbage collector decides to run, so exposing
either would make your code’s behavior depend on garbage-collection timing,
which the spec deliberately refuses to let you observe.
Where this fits
This lesson builds on the same object fundamentals — keys, property
lookup, identity versus value comparison — covered when you learned about
property descriptors; Map and Set are what you reach for once a plain
object’s string-keyed, order-agnostic shape stops being enough. The
WeakMap/WeakSet half connects forward to memory management later in
this roadmap’s advanced group, where garbage collection gets its own
dedicated lesson — this is your first look at why weak references matter
at all.
Check yourself
You try to use a DOM element as a key in a plain object, like `obj[someElement] = "data"`. Why doesn't this behave the way you'd expect?
Plain object keys are always coerced to strings. `someElement` gets converted to something like `"[object HTMLDivElement]"` — the same string for every element of that type — so different elements silently collide onto the same key instead of being distinct entries. `Map` doesn't have this problem because it compares keys by identity, not by a stringified form.
What does `Set` give you that you'd otherwise have to build by hand with an array?
Automatic uniqueness — adding a value that's already in the `Set` is a no-op, so you never end up with duplicates. With a plain array you'd have to manually check `array.includes(value)` before every push to get the same guarantee, and that check gets slower as the array grows.
Why would attaching cache data to a DOM element via a plain `Map` risk a memory leak, where a `WeakMap` wouldn't?
A regular `Map` holds a strong reference to its keys — as long as the `Map` exists, every key it holds stays alive in memory, even after the element is removed from the page and nothing else points to it. A `WeakMap` holds its keys weakly, so once nothing else references that element, the garbage collector can reclaim both the element and its cached entry automatically.
Why can't you iterate over a `WeakMap` or call `.size` on it, the way you can with a regular `Map`?
Because entries can disappear at any moment, whenever the garbage collector decides to reclaim a key nothing else references. Exposing iteration or a size would mean that count could change between two statements for reasons outside your code's control, so the spec deliberately leaves both out.
Why does `Map` preserve insertion order and expose `.size` directly, where a plain object historically didn't?
`Map` was designed from the start specifically as an ordered key/value collection, so iteration order and a live size count were part of its contract from day one. Plain objects were designed as property bags, not collections — later engines standardized an iteration order for object keys, but `.size` still isn't a built-in concept for objects, because counting keys was never their primary job.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.