On this page
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
- tuts/javascript/builtins
- tuts/javascript/builtins/array_and_typed_arrays
- tuts/javascript/builtins/collections_map_set_weak
- tuts/javascript/builtins/Map
- tuts/javascript/builtins/Map/get
- tuts/javascript/builtins/Map/groupBy
- tuts/javascript/builtins/Map/has
- tuts/javascript/builtins/promise_and_async
- tuts/javascript/builtins/Set
- tuts/javascript/builtins/Set/add
- tuts/javascript/builtins/Set/union
- tuts/programming/algorithms_and_dsa/linear_and_hashed_structures
Related notes
- tuts/javascript/builtins Linked here; links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/array_and_typed_arrays Linked here; links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/promise_and_async Linked here; links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Map links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Map/get links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Map/groupBy links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Map/has links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/object_and_reflect Linked here; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Set links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Set/add links to this page; shared tags: #builtins, #javascript, #web