Intermediate · Map, Set, iterators, generators and regular expressions · topic 31 of 61 · 25 min
Map and Set
Explanation
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
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)
}| Object | Map | |
|---|---|---|
| Key types | Strings and symbols | Any value, including objects |
| Size | Object.keys(o).length | m.size |
| Inherited keys | Yes (toString…) | No |
| Order | Mostly insertion order, with integer-like keys first | Always insertion order |
| JSON | Works directly | Convert with Object.fromEntries(m) |
Set
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.
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']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.
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
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.
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 1Practice (0/3 done)
Write unique(list) that returns a new array with duplicates removed, keeping the first occurrence order. Use a Set.
Write wordFrequency(text) that returns a Map from each lower-case word to its count, in the order words first appear.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Iterators and the iteration protocolMap, Set, iterators, generators and regular expressions · same module
- GeneratorsMap, Set, iterators, generators and regular expressions · same module
- Regular expressions: the basicsMap, Set, iterators, generators and regular expressions · same module
- Memory and garbage collectionPerformance and Node.js
- Sets: each item only oncePython Programming · Lists, tuples, dictionaries and sets
- std::map and std::unordered_mapC++ Programming (modern C++ and DSA) · The Standard Template Library (STL)
Questions people ask about this
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.
How do you make an empty set?Related
Answer: set()
{} makes an empty dict. The only way to make an empty set is set().
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.
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.
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
- 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.
- Module 7 exam: Collections, iterators and regular expressions · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Asynchronous JavaScript. 61 topics left in the course before the final exam.