Map, Set, WeakMap, and WeakSet

Dedicated collection types — Map/Set for general keyed/unique-value storage, WeakMap/WeakSet for weakly-held object keys that don't prevent garbage collection.

                new Map() / new Set() / new WeakMap() / new WeakSet()
              

Purpose

Map is a general key/value collection accepting any value as a key. Set stores unique values. WeakMap/WeakSet are their weakly-held counterparts, restricted to object keys that don’t prevent those objects from being garbage collected.

Syntax

const scores = new Map();
scores.set('Ada', 95);
scores.set('Grace', 88);
scores.get('Ada'); // 95
scores.size; // 2
scores.has('Ada'); // true

const uniqueTags = new Set(['js', 'web', 'js']); // duplicates collapse
uniqueTags.size; // 2

const privateData = new WeakMap();
privateData.set(someElement, { clicks: 0 }); // cleaned up automatically once someElement is unreachable

Behavior notes

  • Map preserves insertion order when iterated, and any value — including an object or function — can be a key, unlike a plain object (string/Symbol keys only).
  • Set membership checks (.has()) and Map lookups (.get()/.has()) are both efficient — not a linear scan the way Array.prototype.includes() is.
  • WeakMap/WeakSet cannot be iterated, have no .size, and only accept objects as keys — all deliberate restrictions, since exposing iteration or size would leak information about garbage collection timing, which isn’t observable elsewhere in the language.
  • [...map] (spread) produces an array of [key, value] pairs; [...set] produces an array of its values.

Common mistakes

  • Defaulting to a plain object for general key/value storage out of habit, when the keys aren’t known string identifiers or a Map’s ordering/size guarantees would help.
  • Trying to iterate a WeakMap/WeakSet or read its size — both are unsupported by design.

Runtime notes

Map and Set (ES2015), WeakMap and WeakSet (ES2015), all core ECMAScript with identical behavior across every current browser and Node version.

Taught in these lessons

Related reference