Functions, Scope & Object Model
Map, Set, WeakMap & WeakSet
Map and Set are purpose-built collections for key-value lookup and uniqueness. WeakMap and WeakSet hold object keys weakly, making them useful for metadata that should not prevent garbage collection.
- Map is better than object for arbitrary key-value collections
- Set models uniqueness and membership
- WeakMap keys are weakly held objects
- WeakMap is excellent for private metadata
- Weak collections are not iterable
| Collection | Keys / values | Iterable? | Best use |
|---|---|---|---|
| Map | Any key → value | Yes | Dynamic dictionaries and lookup tables |
| Set | Unique values | Yes | Membership and deduplication |
| WeakMap | Object key → value | No | Object metadata without preventing GC |
| WeakSet | Object values | No | Track object membership weakly |
const usersById = new Map(users.map((user) => [user.id, user]))
const user = usersById.get("u_123")
const seen = new Set()
for (const item of items) {
if (seen.has(item.id)) continue
seen.add(item.id)
process(item)
}const metadata = new WeakMap()
function attachMetadata(node, info) {
metadata.set(node, info)
}
function getMetadata(node) {
return metadata.get(node)
}
// When `node` becomes unreachable elsewhere, WeakMap does not keep it alive.