JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 9: Modern JavaScript SyntaxLesson 45 of 150About 45 minutes

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.

You need: Lesson 30: Building collection-based applications, Lesson 42: Spread and rest syntax

Skills practised: Sets and Maps.

04Explanation

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

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).
Entries
The [key, value] pairs of a Map or object.

Open the full glossary

06Visual learning object

Set operations explorer. Edit two sets and see their union, intersection and difference, and watch duplicates disappear.

Loading the interactive object…

Open the full Set operations explorer page with its guided experiment.

07Examples

ex-045-01Remove duplicates Browser-executable JavaScript

A Set keeps only the first copy of each value.

const visits = ["home", "shop", "home", "cart", "shop"];
const pages = new Set(visits);
console.log(pages.size);
console.log([...pages]);
Sample input
None
Expected output
3 ["home", "shop", "cart"]
Common mistake
Expecting a Set to keep duplicates or to sort the values.
Try this
Count how many visits were repeats.
Source
examples/ex-045-01-unique.js (repository pending publication)

ex-045-02Fast membership checks Browser-executable JavaScript

has answers 'is this in the collection?'.

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.
Try this
Delete linus and print the size.
Source
examples/ex-045-02-membership.js (repository pending publication)

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);
Sample input
None
Expected output
3 undefined Map(5) {"the" => 3, "cat" => 1, "and" => 2, "hat" => 1, "bat" => 1}
Common mistake
Writing counts[w]++, which sets object properties on the Map instead of entries.
Try this
Print only words that appear more than once.
Source
examples/ex-045-03-word-count.js (repository pending publication)

ex-045-04Objects as keys Browser-executable JavaScript

A Map can use objects as keys; a plain object cannot.

const ada = { name: "Ada" };
const grace = { name: "Grace" };
const lastSeen = new Map([[ada, "Mon"], [grace, "Tue"]]);
console.log(lastSeen.get(ada));
console.log(lastSeen.get({ name: "Ada" }));
Sample input
None
Expected output
Mon undefined
Common mistake
Expecting a new object with the same contents to find the entry.
Try this
Loop over lastSeen and print each name and day.
Source
examples/ex-045-04-object-keys.js (repository pending publication)

ex-045-05Convert to and from objects Browser-executable JavaScript

Object.entries and Object.fromEntries bridge Maps and plain objects.

const prices = { tea: 3, cake: 4 };
const map = new Map(Object.entries(prices));
map.set("scone", 2.5);
console.log(map.size);
console.log(Object.fromEntries(map));
console.log(JSON.stringify(map));
Sample input
None
Expected output
3 {tea: 3, cake: 4, scone: 2.5} {}
Common mistake
Sending a Map through JSON.stringify and losing all its data.
Try this
Sort the entries by price before converting back.
Source
examples/ex-045-05-convert.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the unique count

Read a Set's size correctly.

const emails = ["a@example.com", "b@example.com", "a@example.com"];
const unique = new Set(emails);
console.log(`Unique: ${unique.length}`);

Stock levels with a Map

Set, update and read Map entries.

const stock = new Map([["apple", 5], ["pear", 2]]);
// TODO: sell 2 apples, add 10 plums, remove pear
console.log(stock);

Group by category

Build a Map of arrays and a Set of members.

// Write groupByCategory(items) and sharedTags(a, b)

09Prediction

Commit to an answer first, then run the real code to compare.

const s = new Set([1, "1", 1, NaN, NaN]);
console.log(s.size);

What is printed?

10Debugging investigation

Cart quantities are always undefined

The cart stores quantities in a Map, but the summary shows "Mug: undefined" after adding two mugs.

const cart = new Map();
function add(name) {
  cart[name] = (cart.get(name) ?? 0) + 1;
}
add("Mug");
add("Mug");
console.log(`Mug: ${cart.get("Mug")}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Tracking unique visitors

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.
  • Map stores key-value pairs with any key type.
  • Spread a Set or Map to get an array.
  • Convert Maps with Object.fromEntries before JSON.

16AI learning prompts

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 explanation Sets 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 prediction Sets 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.
Debugging Sets 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 generation Sets 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 review Sets 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.