Map, Set, WeakMap & WeakSet
Move beyond standard Objects and Arrays. Learn how to store unique values with Sets and map complex keys with Maps.
Advanced Data Structures
While Arrays and Objects are the workhorses of JavaScript, ES6 introduced four new collection types for specialized tasks: Map, Set, WeakMap, and WeakSet.
Unlike Arrays (which are ordered lists) or Objects (which map strings to values), these structures offer unique memory and iteration constraints.
Set (Unique Values)
A Set is a collection of values where every item must be **completely unique**. If you attempt to .add() a value that already exists, the Set simply ignores it.
Because Sets enforce uniqueness, they are the fastest and easiest way to remove duplicates from an array: const unique = [...new Set([1, 1, 2])].
Map (Any Key Type)
A Map is a key-value store similar to an Object. However, standard Objects only allow strings or Symbols as keys. A Map allows **anything** to be a key - including functions, arrays, or other objects!
Maps also preserve insertion order perfectly and have a built-in .size property, making them much easier to iterate over than standard Objects.
Collection Architecture
Examine the structural differences between an Object, a Map, and a Set to understand when to use each.
Collection Architecture
const arr = [1, 1, 2, 3, 3];
const unique = new Set(arr);
const metadata = new Map();
const domNode = document.querySelector('#btn');
metadata.set(domNode, 'Clicked 5 times');
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
Setis a collection of unique values. It automatically ignores duplicates.- Passing an array into
new Set(arr)is the easiest way to deduplicate it. Mapis a key-value store that allows ANY data type to be used as a key (even objects).- Maps preserve insertion order and provide a direct
.sizeproperty. WeakMapandWeakSetprevent memory leaks by allowing their contents to be garbage collected.
Done with this concept?
Mark it complete to track your progress. No login needed.