On this page
  1. Collections: Map, Set, WeakMap & WeakSet
  2. Contents
  3. Map vs. Plain Objects
  4. Set & Set Algebra
  5. WeakMap & WeakSet

Collections: Map, Set, WeakMap & WeakSet

Prev: Array & Typed Arrays | Up: builtins | Next: Promise & Async
Rel: Object & Reflect
Ref: MDN Web Docs — Keyed Collections
Tags: #public #web #javascript #builtins


Contents


Map vs. Plain Objects

Prefer Map for dynamic key-value stores: keys can be any value (including objects), insertion order is guaranteed, .size is $O(1)$, and there are no prototype-key collisions.

const cache = new Map([["a", 1], ["b", 2]]);
cache.set("c", 3);
for (const [k, v] of cache) {
  console.log(k, v);
}

Set & Set Algebra

const a = new Set(["html", "css", "js"]);
const b = new Set(["js", "python"]);

a.union(b);        // Set { 'html', 'css', 'js', 'python' }
a.intersection(b); // Set { 'js' }
a.difference(b);   // Set { 'html', 'css' }

WeakMap & WeakSet

Keys in WeakMap (and values in WeakSet) must be objects or non-registered symbols and are held weakly so they do not prevent garbage collection — ideal for attaching private metadata to DOM nodes.

Linked from

Related notes