Map, Set, WeakMap & WeakSet
Keyed collections, unique values, the new Set methods and when weak references help.
Arrays and plain objects cover most needs, but JavaScript has four more specialised collections: Map (key–value pairs with any kind of key), Set (unique values), and their "weak" cousins WeakMap and WeakSet. Picking the right one makes code shorter, faster and less buggy.
Map: key–value pairs, any key#
Create a Map from pairs, or from an object with Object.entries:
Any value can be a key
This is Map's superpower. Object keys are always converted to strings; Map keys keep their type and identity:
Iterating a Map
Maps remember insertion order and are directly iterable:
Example: counting with a Map
Grouping into a Map
Map.groupBy (ES2024) is like Object.groupBy but produces a Map, so the group keys can be anything:
Map or object?
Set: unique values#
Removing duplicates
The most common use of a Set:
Fast membership checks
set.has(x) is near-instant even with millions of items, while array.includes(x) checks every element:
Set operations (ES2025)
Modern engines (Node 22+, current browsers) have built-in set maths:
In older environments, the equivalent is new Set([...a].filter((x) => b.has(x))) for intersection, and so on.
Sets compare values with
===semantics (except thatNaNequalsNaN). Two different objects with the same contents are two entries:new Set([{}, {}]).sizeis2.
WeakMap and WeakSet#
A normal Map keeps its keys alive: as long as the Map exists, its key objects can't be garbage-collected. That's a memory leak if you use objects (like DOM elements) as keys and forget to delete them.
WeakMap holds its keys weakly: if nothing else references a key object, the entry silently disappears.
Restrictions (which follow from "entries can vanish at any time"):
- Keys must be objects (or non-registered symbols), not strings or numbers.
- No
size, no iteration, noclear()— onlyget,set,has,delete.
Use case: private data or caches for objects
When report is no longer used anywhere, its cached summary is freed too.
Use case: data attached to DOM elements
WeakSet
A WeakSet is a set of objects held weakly — useful for "have I seen/processed this object?":
Quick reference#
Common mistakes#
- Using
map[key] = valueon a Map — that sets an ordinary property, not an entry. Usemap.set(key, value). - Expecting
JSON.stringify(map)to work — it gives{}. Convert withObject.fromEntries(map)first. - Using objects as Set members and expecting content-based de-duplication.
- Reaching for WeakMap when you need to list or count entries — use a Map.
What's next#
Next: regular expressions — a mini-language for searching, validating and transforming text.
Check your understanding
Quick quiz
1.What is
new Set([1, 2, 2, 3, 3, 3]).size?2.Which is a real advantage of
Mapover a plain object for a lookup table?3.Why would you use a
WeakMapto store extra data about DOM elements?
Finished reading?
Mark this lesson complete to track your progress.