Keyed collections in JavaScript mainly refer to:

  • Map
  • WeakMap
  • Set
  • WeakSet

They are useful when plain objects or arrays are not the best fit.

Map

Basic usage

Map stores key-value pairs and allows keys of any type.

const map = new Map();
map.set("name", "Tom");
map.set(1, "one");
map.set(true, "yes");
console.log(map.get("name")); // "Tom"
console.log(map.has(1)); // true
console.log(map.size); // 3

Compared with Object

Map is usually a better choice when:

  • keys are not just strings
  • insertion order matters
  • you need frequent additions and deletions
  • you want a dedicated collection API

WeakMap

WeakMap only accepts objects as keys.

const wm = new WeakMap();
const user = {};
wm.set(user, { cached: true });
console.log(wm.get(user));

Important characteristics:

  • keys must be objects
  • keys are weakly held
  • not enumerable

WeakMap is commonly used for:

  • private-like metadata
  • object-related cache data

Set

Basic usage

Set stores unique values.

const set = new Set([1, 2, 2, 3]);
console.log(set); // Set {1, 2, 3}
set.add(4);
set.delete(2);
console.log(set.has(1)); // true

Convert with arrays and remove duplicates

const arr = [1, 2, 2, 3, 3];
const unique = [...new Set(arr)];

Set operations

const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);
const union = new Set([...a, ...b]);
const intersection = new Set([...a].filter((x) => b.has(x)));
const difference = new Set([...a].filter((x) => !b.has(x)));

Compared with arrays

Set is useful when:

  • uniqueness matters
  • repeated has checks matter
  • you do not care about index-based access

WeakSet

WeakSet is similar to WeakMap, but it stores only objects and no values.

const weakSet = new WeakSet();
const obj = {};
weakSet.add(obj);
console.log(weakSet.has(obj)); // true

It is often used to mark objects:

  • already processed
  • already visited
  • special internal state

Equality: SameValueZero

Map and Set use the SameValueZero rule for equality.

That means:

  • NaN is considered equal to NaN
  • 0 and -0 are treated as equal

Practical Advice

  • Use Map when keys are not naturally object property names
  • Use Set when you need uniqueness
  • Use WeakMap or WeakSet when keys should not prevent garbage collection

Reference

  • MDN: Map
  • MDN: Set
  • MDN: WeakMap
  • MDN: WeakSet