This chapter follows Set in JavaScript.
Map is an ordered key/value store. Keys can be any value (objects, primitives, symbols). WeakMap only accepts object keys (and, since ES2023, symbols); keys are held weakly so entries disappear when nothing else references the key object.
Map essentials
| API | Notes |
|---|---|
new Map(iterable?) |
From [key, value] pairs |
set(key, value) |
Returns the map (chainable) |
get(key), has(key), delete(key) |
Lookup and removal |
clear(), size |
Reset; entry count |
keys(), values(), entries() |
Iterators; for..of yields entries |
const map = new Map([ ["name", "Ada"], ["year", 1815],]);map.set({ id: 1 }, "metadata");map.get("name"); // "Ada"map.size; // 3Insertion order is preserved when iterating—unlike ordinary objects, where integer-like keys sort first.
When Map beats {}
- Keys are objects, functions, or mixed types—not only strings/symbols.
- You need reliable size and frequent add/delete without touching prototype pollution concerns.
- You iterate entries in insertion order and do not need JSON serialization of the map itself.
Plain objects remain fine for fixed, string-keyed records and JSON payloads.
WeakMap essentials
| Property | WeakMap |
|---|---|
| Keys | Objects (and symbols in modern engines) |
size |
Not exposed |
| Iteration | Not iterable—no keys() |
| GC | Key object collected → entry removed |
const cache = new WeakMap();let obj = { id: 1 };cache.set(obj, { computed: 42 });cache.get(obj); // { computed: 42 }obj = null; // entry may be collected; no way to list itTypical uses: private metadata on DOM nodes or class instances, caches keyed by request objects, and breaking reference cycles without leaking memory.
WeakMap vs Map vs Set
| Map | WeakMap | Set | |
|---|---|---|---|
| Values | key → value | key → value | value only |
| Key types | Any | Object/symbol | N/A |
| Iterable | Yes | No | Yes |
size |
Yes | No | Yes |
For ordered unique values, use Set. For numeric indexed lists, use Arrays.
Continue with Typed arrays and ArrayBuffer.