Skip to content

Intermediate · Map, Set, iterators, generators and regular expressions · topic 31 of 61 · 25 min

Map and Set

Explanation

A Map stores key-value pairs where the key can be any value, keeps insertion order, and has a size. A Set stores unique values only, which makes removing duplicates and checking membership fast. WeakMap and WeakSet hold objects without stopping them from being garbage-collected.

Why not just use objects and arrays?

Plain objects work as dictionaries, but their keys are always strings, they inherit keys like toString from Object.prototype, and counting their entries needs Object.keys(obj).length. Arrays can hold unique values, but checking includes on a big array means scanning every item. Map and Set (ES2015) are built exactly for these jobs.

Map

javascript
const stock = new Map();
stock.set('rice', 40);
stock.set('dal', 25);
console.log(stock.get('rice'));   // 40
console.log(stock.has('oil'));    // false
console.log(stock.size);          // 2
stock.delete('dal');

const visits = new Map();
const user = { id: 7 };
visits.set(user, 3);              // an OBJECT as a key
console.log(visits.get(user));    // 3

for (const [item, qty] of new Map([['a', 1], ['b', 2]])) {
  console.log(item, qty);         // a 1, then b 2 (insertion order)
}
ObjectMap
Key typesStrings and symbolsAny value, including objects
SizeObject.keys(o).lengthm.size
Inherited keysYes (toString…)No
OrderMostly insertion order, with integer-like keys firstAlways insertion order
JSONWorks directlyConvert with Object.fromEntries(m)

Set

javascript
const tags = new Set(['veg', 'spicy', 'veg']);
console.log(tags.size);            // 2: duplicates are dropped
tags.add('jain');
console.log(tags.has('spicy'));    // true (fast, even for millions of items)

const pins = ['411001', '400001', '411001'];
const unique = [...new Set(pins)]; // ['411001', '400001']

Set operations

Combining sets is common: customers who bought both products (intersection), everyone who bought either (union), people on list A but not B (difference). ES2025 added methods for this: a.union(b), a.intersection(b) and a.difference(b). They are in current browsers and recent Node; in older environments use filter as below.

javascript
const bought = new Set(['Asha', 'Ravi', 'Meena']);
const reviewed = new Set(['Ravi', 'Kabir']);
const both = [...bought].filter((n) => reviewed.has(n));          // ['Ravi']
const either = new Set([...bought, ...reviewed]);                  // 4 names
const notReviewed = [...bought].filter((n) => !reviewed.has(n));  // ['Asha', 'Meena']
Careful: Set and Map compare keys with SameValueZero, which works like === for objects. new Set([{ id: 1 }, { id: 1 }]).size is 2, because they are two different objects. To dedupe objects, use a Map keyed by an id: new Map(list.map((o) => [o.id, o])).

WeakMap and WeakSet

A WeakMap only accepts objects as keys and does not keep them alive. When nothing else refers to the key object, the garbage collector can remove it and its entry. This is useful for caches and for attaching extra data to objects you do not own. WeakMaps cannot be looped over and have no size.

Think of it like this: A Map is like a cloak-room counter with token numbers: any kind of token works, and you can count how many coats are there. A Set is like the guest list at a wedding gate: each name appears once, and checking a name is quick.
Tip: Choose quickly: lookup by key → Map; "have I seen this?" or uniqueness → Set; fixed record shape (user with name and city) → plain object.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Map and Set · 1/6

Map and Set

In this lesson you will use Map and Set, collections built for lookups and unique values.

Prefer a video by a teacher? Find free videos on “javascript map and set explained weakmap” on YouTube ↗

In real life: Counting unique visitors on a news site

A news website logs every page view with a user id. The editors want total views per article and the number of unique readers. A Map holds the counts per article, and a Set per article holds the reader ids so repeat visits are not double counted.

javascript
const views = [['a1', 'u1'], ['a1', 'u2'], ['a1', 'u1'], ['a2', 'u3']];
const readers = new Map();
for (const [article, user] of views) {
  if (!readers.has(article)) readers.set(article, new Set());
  readers.get(article).add(user);
}
console.log(readers.get('a1').size, readers.get('a2').size); // 2 1

Practice (0/3 done)

Task 1 · Code · Javascript

Write unique(list) that returns a new array with duplicates removed, keeping the first occurrence order. Use a Set.

Task 2 · Code · Javascript

Write wordFrequency(text) that returns a Map from each lower-case word to its count, in the order words first appear.

Task 3 · Code · Javascript

Write commonCustomers(listA, listB) that returns the names present in BOTH arrays, in listA order, without duplicates. Use a Set for fast lookups.

Quick quiz

Question 1

1.What is new Set([1, 1, 2]).size?

Question 2

2.Which can use an object as a key?

Question 3

3.new Set([{ a: 1 }, { a: 1 }]).size is…

Question 4

4.Why use a WeakMap for a cache keyed by objects?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is new Set([1, 1, 2]).size?

Answer: 2

Sets store unique values only.

Which can use an object as a key?

Answer: A Map

Map keys can be any value; plain object keys become strings.

new Set([{ a: 1 }, { a: 1 }]).size is…

Answer: 2

The two objects are different references, so both are kept.

Why use a WeakMap for a cache keyed by objects?

Answer: Entries do not keep the key objects alive

WeakMap entries disappear when the key object is no longer used elsewhere.

Why use a WeakMap to attach data to DOM elements?Related

Answer: Entries disappear when the element is gone

Weak keys do not keep the element alive.

From Memory and garbage collection

How do you make an empty set?Related

Answer: set()

{} makes an empty dict. The only way to make an empty set is set().

From Sets: each item only once

How do you read a value from a const std::map without risk of insertion?Related

Answer: m.at(key) or m.find(key)

operator[] is not allowed on const maps because it may insert; at and find are.

From std::map and std::unordered_map

Which Python list operation is O(n)?Related

Answer: a.pop(0)

pop(0) removes the first item, so every other item shifts one place left.

From The real cost of Python and JavaScript built-ins

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Map, Set, iterators, generators and regular expressions” before its exam: Iterators and the iteration protocol, Generators, Regular expressions: the basics, Regular expressions in practice.
  2. Module 7 exam: Collections, iterators and regular expressions · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Asynchronous JavaScript. 61 topics left in the course before the final exam.

← Previous: Formatting numbers, money and text with Intl