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 choice
CollectionKeys / valuesIterable?Best use
MapAny key → valueYesDynamic dictionaries and lookup tables
SetUnique valuesYesMembership and deduplication
WeakMapObject key → valueNoObject metadata without preventing GC
WeakSetObject valuesNoTrack object membership weakly
Map and Set basics
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)
}
Use Map for lookup and Set for membership instead of repeatedly scanning arrays.
WeakMap metadata
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.
WeakMap is useful when the object owns the lifetime, not the metadata table.
Sources
  • MDN JavaScript Guide and ReferenceKeyed collections
  • The Modern JavaScript TutorialMap and Set; WeakMap and WeakSet
  • Eloquent JavaScript, 4th EditionData Structures