Skip to content

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.

14 min read0/5 questions

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).

JavaScript
// 1. Keys are always converted to stringsconst seats = {};seats[1] = "Ada";seats["1"] = "Sam"; // same key as 1console.log(Object.keys(seats), seats[1]); // 2. Object keys collapse into one stringconst alice = { name: "Alice" };const bob = { name: "Bob" };const notes = {};notes[alice] = "likes tea";notes[bob] = "likes coffee";console.log(Object.keys(notes), notes[alice]); // 3. Inherited properties look like dataconst wordCount = {};console.log("constructor" in wordCount, typeof wordCount.toString); // 4. Integer-like keys are reorderedconst ranking = { b: 1, 20: "x", a: 2, 3: "y" };console.log(Object.keys(ranking));
Output
Press Run (⌘ Enter) to see what happens.

Each line shows a real bug waiting to happen:

  1. The number 1 and the string "1" are the same key, because object keys are always strings (or symbols).
  2. Every object becomes the string "[object Object]" when used as a key, so Alice's note is overwritten by Bob's.
  3. Every plain object inherits properties such as constructor and toString. If you count words in a text that contains the word "constructor", the check if (counts[word]) finds a function instead of a number.
  4. 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.

Predict the outputJavaScript

What does this print?

const scores = {};
scores[7] = "first";
scores["7"] = "second";
console.log(Object.keys(scores).length, scores[7]);
Need a nudge? Hints walk you through it.

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.

JavaScript
const prices = new Map([ ["apple", 0.5], ["pear", 0.75],]); prices.set("plum", 0.4).set("fig", 1.2); // set returns the map, so it chainsconsole.log(prices.get("pear"), prices.get("kiwi"));console.log(prices.has("fig"), prices.size);prices.delete("apple"); // Loop over [key, value] pairs, in insertion orderfor (const [fruit, price] of prices) { console.log(`${fruit}: $${price.toFixed(2)}`);} // Objects as keys: matched by reference (the same object), not by contentsconst alice = { name: "Alice" };const notes = new Map([[alice, "likes tea"]]);console.log(notes.get(alice), notes.get({ name: "Alice" })); // Converting between objects and Mapsconst fromObject = new Map(Object.entries({ small: 2, large: 4 }));console.log(Object.fromEntries(fromObject));
Output
Press Run (⌘ Enter) to see what happens.

The main methods:

MethodDoes
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
sizeHow 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.

Quick check
What does the last line log?
const cache = new Map();
cache.set({ id: 1 }, "Ada");
console.log(cache.get({ id: 1 }));
Need a nudge? A hint rules out a wrong answer.

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.

JavaScript
// Dedupe in one lineconst tags = ["js", "css", "js", "html", "css"];console.log([...new Set(tags)]); // Fast "have I seen this?" checksconst seen = new Set();for (const email of ["a@x.com", "b@x.com", "a@x.com"]) { if (seen.has(email)) console.log("duplicate:", email); seen.add(email);} // Set operations (ES2025, in all current browsers and Node 22+)const mine = new Set(["js", "css", "react"]);const job = new Set(["js", "react", "node"]);console.log([...mine.intersection(job)]);console.log([...job.difference(mine)]);console.log([...mine.union(job)].length);
Output
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()].

Predict the outputJavaScript

What does this print?

const s = new Set([3, 1, 3, "3", 1]);
s.add(1);
console.log(s.size, [...s].join(" "));
Need a nudge? Hints walk you through it.

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".

Counting votes with a Map

puthash("tea") % 6 = 2

  1. 0empty
  2. 1empty
  3. 2"tea":1
  4. 3empty
  5. 4empty
  6. 5empty

First vote: counts.get("tea") is undefined, so ?? 0 gives 0. Set it to 1.

1/5
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.

Match the pairs0/5 matched

Pick the best collection for each job.

Choose an item, then its match on the other side.

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.

Quick check
Why can't you loop over a WeakMap or read its size?
Need a nudge? A hint rules out a wrong answer.
Key terms
Map
A key and value collection with keys of any type, insertion order and a size property.
Set
A collection of unique values with fast has, add and delete.
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.