Lesson 45: Sets, Maps and modern collection patterns
01Opening question
You need to know whether a username is already taken, and how many times each word appears in a review. Is an array the best tool for either?
Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.
02Start with working code
A Set stores each value once; a Map stores values under keys.
const tags = new Set(["js", "css", "js"]);
console.log(tags.size, tags.has("css"));
const stock = new Map();
stock.set("apple", 12);
stock.set("pear", 0);
console.log(stock.get("apple"), stock);
03Objective and prerequisites
Learning objective: Use Set for unique values and fast membership checks, Map for key-value data with any key type, and convert between them and arrays.
A Set holds unique values. add ignores duplicates, has checks membership, delete removes a value and size counts them.
[...new Set(list)] is the standard way to remove duplicates from an array.
A Map stores key-value pairs: map.set(key, value), map.get(key), map.has(key), map.delete(key) and map.size.
Loop over either with for...of. A Map gives [key, value] pairs: for (const [word, count] of counts).
Map keys can be any value (objects, numbers) and keep insertion order; plain object keys are always strings or symbols and can collide with inherited names like constructor.
Set and Map compare keys with SameValueZero: NaN matches NaN, but two different objects with the same contents are different keys.
set.has(x) is typically constant time, while array.includes(x) scans the array. For repeated lookups in large lists, build a Set once.
Maps and Sets do not convert to JSON directly: JSON.stringify(new Map()) gives {}. Convert with Object.fromEntries(map) or [...set] first.
05Definitions
Set
A collection of unique values.
Map
A collection of key-value pairs where keys can be any type.
Membership check
Testing whether a value is in a collection, e.g. set.has(value).
const taken = new Set(["ada", "grace", "linus"]);
for (const name of ["alan", "grace"]) {
console.log(name, taken.has(name) ? "taken" : "available");
}
taken.add("alan");
console.log(taken.size);
Sample input
None
Expected output
alan available
grace taken
4
Common mistake
Using taken[name], which reads a property, not a member.
ex-045-03Count with a Map Browser-executable JavaScript
get with a fallback plus set is the counting pattern.
const words = "the cat and the hat and the bat".split(" ");
const counts = new Map();
for (const w of words) {
counts.set(w, (counts.get(w) ?? 0) + 1);
}
console.log(counts.get("the"), counts.get("dog"));
console.log(counts);
An analytics page counts unique visitors with a Set and page views per path with a Map. Both update in constant time per event, and are converted to arrays or objects only when the report is saved as JSON.
const visitors = new Set();
const views = new Map();
for (const [user, path] of [["u1", "/"], ["u2", "/"], ["u1", "/shop"]]) {
visitors.add(user);
views.set(path, (views.get(path) ?? 0) + 1);
}
console.log(visitors.size, Object.fromEntries(views));
12Knowledge check
1. What is printed?
const s = new Set(["a", "b", "a"]);
console.log(s.size);
3
2
1
0
2. What is printed?
const s = new Set([{ id: 1 }]);
console.log(s.has({ id: 1 }));
true
false
undefined
An error
3. Which is a reason to choose a Map over a plain object?
Maps are always faster to print
Keys can be any type and size is built in
Maps convert to JSON automatically
Objects cannot hold numbers
4. Why does this print undefined?
const m = new Map([["a", 1]]);
console.log(m["a"]);
Maps use get, not brackets
The key is misspelled
Maps cannot store numbers
set returns undefined
5. What is printed?
const s = new Set();
s.add("x").add("y").add("x");
console.log([...s]);
["x", "y"]
["y", "x"]
{x, y}
2
6. You check 10,000 order ids against a list of 5,000 refunded ids. Which is better?
refunded.includes(id) for each order
Build refundedSet = new Set(refunded), then refundedSet.has(id)
Sort both and compare strings
JSON.stringify both
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Fix the unique count: Prints Unique: 2
Stock levels with a Map: Prints the stock; No pear
Group by category: Prints groups and shared tags; Empty input; No shared tags
ex-045-01: output matches the documented expected output
ex-045-02: output matches the documented expected output
ex-045-03: output matches the documented expected output
ex-045-04: output matches the documented expected output
ex-045-05: output matches the documented expected output
The lesson lives in the companion repository at curriculum/level-02-core-development/module-09-modern-javascript-syntax/lesson-045-sets-maps-and-modern-collection-patterns/. Every example on this page is generated from those files.
The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.
15Summary and next steps
Set stores unique values; has, add, delete and size.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationSets and Maps
Context: I am learning Sets and Maps in JavaScript.
Task: Explain Set and Map with examples of unique visitors and word counts, and when to choose them over arrays and objects.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionSets and Maps drill
Context: I have practised Sets and Maps.
Task: Give me six snippets with Set and Map, including object keys and NaN, and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
DebuggingSets and Maps bug
Context: My Map lookups return undefined even though I added the data.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationSets and Maps practice
Context: I finished the Sets and Maps exercises.
Task: Create three exercises that count, group and de-duplicate data with Set and Map.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewSets and Maps review
Context: Here is my code that uses Sets and Maps.
Task: Review my code for arrays and objects that would be clearer or faster as a Set or Map.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.