Map & Set
Objects and arrays cover a lot of ground, but JavaScript has two purpose-built collections that do specific jobs better: Map for key/value pairs with any key type, and Set for collections of unique values.
Learn Map & Set in our free JavaScript course — a beginner-friendly interactive lesson with runnable examples, a practice exercise and a quick recall.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Knowing when to reach for them — deduplicating a list, counting occurrences, caching by object key — is a hallmark of fluent, professional code.
What You'll Learn in This Lesson
📚 Prerequisites: Be comfortable with objects, arrays, and spread syntax — we use [...set] to convert collections back to arrays.
💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a .html file with <script> tags and open it in your browser
🗄️ Real-World Analogy: Think of two kinds of storage:
- • A Map is a labelled filing cabinet — each drawer (key) holds one file (value), and labels can be anything
- • A Set is a guest list at the door — every name appears once , no duplicates allowed
- • Need to look up "the value for this key"? Use a Map
- • Need "the unique collection of these things"? Use a Set
1️⃣ Map — Key/Value, the Right Way
A Map stores key/value pairs. You add with set(key, value) , read with get(key) , check with has(key) , remove with delete(key) , and count with the size property. Crucially, it remembers insertion order .
2️⃣ Map Keys Can Be Anything
This is a Map's superpower over a plain object. Object keys are always coerced to strings, but a Map can use objects, functions, numbers, even booleans as keys. That makes it perfect for attaching data to specific object instances — a lightweight cache, for example.
3️⃣ Iterating a Map
Maps are directly iterable in insertion order. Loop pairs with for...of (destructuring each [key, value] ), or use map.keys() , map.values() , and map.entries() . Convert to an array with the spread operator when you need array methods.
🎯 Your Turn #1 — Build a Phone Book
4️⃣ Set — A Collection of Unique Values
A Set holds unique values — add a duplicate and it's silently ignored. You add with add(value) , test with has(value) , remove with delete(value) , and count with size . Membership checks are fast and read beautifully.
5️⃣ The Killer One-Liner: Deduplicate an Array
The most common reason to reach for a Set: removing duplicates from an array. Wrap the array in a Set to drop repeats, then spread it back into an array. One line, no nested loops.
6️⃣ Set Math: Union, Intersection & Difference
Sets make classic "which items are in both lists / only this list" questions easy. Combine with spread for a union, and filter + has for intersection and difference.
🎯 Your Turn #2 — Remove Duplicates
🧩 Reorder Challenge
These lines are scrambled. Reorder them so it logs the unique count 3 .
Why: the Set must exist before you add to it, and the duplicate "red" is ignored — so the final size is 3.
🧠 Quick Recall
Predict the output before revealing the answer.
3 — a Set keeps only unique values: 1, 2, and 3.
9 — setting an existing key overwrites its value; set returns the Map so you can chain.
2 — objects are compared by reference, so two different {} objects are distinct values.
Common Errors & Fixes
- 1️⃣ Using .length or () on size
- 2️⃣ Reading a Map with bracket notation
- 3️⃣ Expecting object-keyed Sets to dedupe by content
- 4️⃣ Forgetting to spread back to an array
Quick Reference — Map & Set
Task
Map
Set
Create
new Map()
new Set()
Add
map.set(k, v)
set.add(v)
Read
map.get(k)
set.has(v)
Check
map.has(k)
Remove
map.delete(k)
set.delete(v)
Count
map.size
set.size
Frequently Asked Questions
Lesson Complete — Map & Set!
- ✅ Map = key/value with any key type and reliable order
- ✅ Set = unique values; [...new Set(arr)] deduplicates
- ✅ Count with the .size property; both are iterable with for...of
- ✅ Use Set math for union, intersection, and difference
Up next: a Checkpoint to put the whole core toolkit together. 🏁
Practice quiz
How do you count the items in a Map or Set?
- The .length property
- The .size property
- The .count() method
- The .size() method
Answer: The .size property. Maps and Sets expose .size as a property (no parentheses); .length is for arrays.
What is logged? const m = new Map(); m.set(1, 'a'); m.set('1', 'b'); console.log(m.size);
- 1
- 2
- undefined
- It throws
Answer: 2. A Map keeps the number 1 and the string '1' as distinct keys, so the size is 2.
What is the idiomatic one-liner to remove duplicates from an array named tags?
- tags.unique()
Wrapping an array in a Set drops duplicates; spreading it back gives a deduplicated array.
How does a Set decide whether two values are duplicates?
- By deep content comparison
- Using SameValueZero (=== with NaN equal to NaN)
- By converting both to strings
- By their .toString() output
Answer: Using SameValueZero (=== with NaN equal to NaN). Sets use SameValueZero: essentially === except NaN equals NaN. Objects compare by reference.
What is logged? const s = new Set(); s.add({}); s.add({}); console.log(s.size);
- 0
- 1
- 2
- It throws
Answer: 2. Objects are compared by reference, so two different {} objects are two distinct values.
Which method reads a value from a Map by its key?
- map.read(key)
Use map.get(key). Bracket notation sets a plain property instead of a Map entry.
What advantage does a Map have over a plain object for keys?
- Keys can be any type, including objects
- Keys are always sorted alphabetically
- Keys must be strings
- Keys cannot be deleted
Answer: Keys can be any type, including objects. Object keys are coerced to strings, but a Map can use objects, functions, numbers, and booleans as keys.
What is logged? m.set('a', 1).set('a', 9); console.log(m.get('a'));
- 1
- 9
Answer: 9. Setting an existing key overwrites its value, and set returns the Map so calls can be chained.
Given a = new Set([1,2,3,4]) and b = new Set([3,4,5,6]), what is the intersection [...a].filter(x => b.has(x))?
Intersection keeps values present in both sets: 3 and 4.
How do you loop over a Map's key/value pairs in insertion order?
Maps are iterable in insertion order; for...of with [key, value] destructuring reads each pair.
Continue this course
- Previous: Scope & var/let/const (the TDZ)
- Next: Checkpoint: Core JavaScript