Lesson 12 of 50JavaScript in depth
Maps and Sets
Know when a Map beats a plain object, use Sets for uniqueness and fast lookups, and apply both to counting, deduping and caching.
The arrays and objects lesson introduced Map and Set in a few lines: a Map is a dictionary whose keys can be anything, and a Set holds unique values. That is the right first picture, but these two collections earn a full lesson because they quietly fix a whole category of bugs. A plain object used as a dictionary turns your keys into strings, mixes your data with built-in properties, and sorts some keys in an order you did not choose. This lesson shows exactly where objects go wrong, how Maps and Sets behave, how to loop over them, and the three jobs where they shine: counting, removing duplicates, and caching.
Where plain objects fall short
A plain object works fine as a record with a fixed shape, like { id, name, email }. It starts to misbehave when you use it as a dictionary, a collection whose keys you only find out while the program runs (user ids, words in a document, product codes).
Press Run (⌘ Enter) to see what happens.Each line shows a real bug waiting to happen:
- The number
1and the string"1"are the same key, because object keys are always strings (or symbols). - Every object becomes the string
"[object Object]"when used as a key, so Alice's note is overwritten by Bob's. - Every plain object inherits properties such as
constructorandtoString. If you count words in a text that contains the word "constructor", the checkif (counts[word])finds a function instead of a number. - Keys that look like whole numbers are listed first, in numeric order, before the other keys in insertion order.
A Map has none of these problems.
What does this print?
const scores = {};
scores[7] = "first";
scores["7"] = "second";
console.log(Object.keys(scores).length, scores[7]);The Map API
A Map stores key and value pairs. Keys can be any value: strings, numbers, booleans, objects, even functions. It remembers insertion order and tracks its own size.
Press Run (⌘ Enter) to see what happens.The main methods:
| Method | Does |
|---|---|
new Map(pairs) | Creates a Map, optionally from an array of [key, value] pairs |
set(key, value) | Adds or replaces. Returns the Map, so calls chain |
get(key) | The value, or undefined if the key is missing |
has(key) / delete(key) | Check for, or remove, a key |
size | How many entries (a property, not a method) |
keys(), values(), entries() | Iterators for looping |
Two rules matter in practice. First, use get and set, never square brackets. map["apple"] = 1 sets a normal property on the Map object, which get cannot see. Second, object keys match by reference: a new object with the same contents is a different key, as the last lookup above shows. Primitive keys (strings, numbers) match by value, and unlike ===, a Map even treats NaN as equal to itself.
const cache = new Map();
cache.set({ id: 1 }, "Ada");
console.log(cache.get({ id: 1 }));Iterating
Maps are iterable, so for...of gives you [key, value] pairs directly, as above. map.keys() and map.values() give just one side. These return iterators, not arrays, so they have no map or filter. Spread them into an array first: [...prices.keys()], or [...prices].filter(([fruit, price]) => price < 1).
Sets: unique values
A Set is a collection where every value appears at most once. Adding a value that is already there does nothing. Its methods are add, has, delete and the size property, and it iterates in insertion order.
The killer feature is speed. set.has(x) takes about the same time whether the Set holds ten values or ten million, because, like a Map, it is built on a hash table (a structure that jumps straight to where a value is stored). array.includes(x) has to check elements one by one. If you check membership inside a loop, that difference turns seconds into milliseconds.
Press Run (⌘ Enter) to see what happens.The set operations at the end arrived in 2024 browsers and are part of ES2025: union, intersection, difference, symmetricDifference, plus checks like isSubsetOf. If your code must run on older browsers, check MDN or Can I Use first; the fallback is a filter: [...a].filter((x) => b.has(x)) for an intersection.
One catch: like Map keys, Set values that are objects are compared by reference. new Set([{ id: 1 }, { id: 1 }]) has a size of 2. To remove duplicate objects by their id, build a Map keyed by id: [...new Map(users.map((u) => [u.id, u])).values()].
What does this print?
const s = new Set([3, 1, 3, "3", 1]);
s.add(1);
console.log(s.size, [...s].join(" "));Common jobs
Counting
Counting how often each thing appears is one of the most common tasks in programming: word frequencies, votes, page views, errors by type. With a Map, the pattern is "get the current count, or 0, and add one".
First vote: counts.get("tea") is undefined, so ?? 0 gives 0. Set it to 1.
const counts = new Map();
for (const vote of votes) {
counts.set(vote, (counts.get(vote) ?? 0) + 1);
}For grouping (not just counting), modern JavaScript has Map.groupBy(items, fn), which returns a Map from each group key to an array of items (ES2024, in current browsers and Node 21+).
Caching
A cache remembers answers you have already worked out so you do not repeat expensive work. A Map is the natural store: the input is the key and the answer is the value.
const userCache = new Map();
async function getUser(id) {
if (userCache.has(id)) return userCache.get(id);
const user = await fetchUserFromServer(id);
userCache.set(id, user);
return user;
}A cache that only ever grows is a memory leak: the program holds onto data it no longer needs. Real caches set a size limit or an expiry time. Because a Map remembers insertion order, a simple limit is easy: when size is too big, delete the first key from cache.keys().next().value, which is the oldest entry.
Pick the best collection for each job.
Replacing slow nested searches
The biggest everyday win from Sets and Maps is speed in code that compares two lists. Say you have 5,000 orders and 5,000 customers, and you want each order with its customer's name. The obvious version calls customers.find((c) => c.id === order.customerId) inside a loop over orders. Each find may scan all 5,000 customers, so the whole job can take 25 million comparisons, enough to make a page stutter.
Build a lookup first instead: const byId = new Map(customers.map((c) => [c.id, c])). Building it walks the customers once. After that, each byId.get(order.customerId) is a single jump, so the whole job is about 10,000 steps instead of 25 million. The same idea works with a Set when you only need a yes or no answer, such as "is this product in the user's wishlist?". This "build an index, then look up" move is one of the most common optimisations in real code and in coding interviews, where it often turns a slow nested loop answer into a fast one.
WeakMap and WeakSet
A WeakMap is a Map whose keys must be objects, and it holds them weakly: if nothing else in your program still refers to a key object, the garbage collector (the part of the engine that frees unused memory) can remove it, and its entry disappears with it. That makes WeakMaps ideal for attaching private or cached data to objects you do not own, such as DOM elements or objects from a library, without keeping them alive forever. The trade-off is that you cannot loop over a WeakMap or ask its size, because entries could vanish at any moment. WeakSet is the same idea for "have I already handled this object?" flags. You will reach for these rarely, but when you need them, nothing else does the job.
- Map
- A key and value collection with keys of any type, insertion order and a
sizeproperty. - Set
- A collection of unique values with fast
has,addanddelete. - dictionary
- A collection whose keys are only known while the program runs, like word counts or a cache.
- hash table
- The structure behind Map and Set that finds a key in about the same time however many there are.
- cache
- Stored results of earlier work, looked up by input, so the work is not repeated.
- WeakMap
- A Map with object keys held weakly, so entries vanish when the key object is garbage collected. Not iterable.