Map & Set
in JavaScript
Master key-value storage with Map and unique membership with Set: two powerful built-in data structures that go beyond plain objects and arrays.
Why Go Beyond Objects & Arrays?
Plain objects ({}) and arrays ([]) are everywhere in JavaScript, but they have limits. Objects only accept string or Symbol keys, and arrays don't enforce uniqueness. Map and Set solve these problems with purpose-built APIs.
What Is a Map?
A Map is an ordered collection of key-value pairs where keys can be any type: strings, numbers, objects, or even other Maps.
What Is a Set?
A Set is an ordered collection of unique values. If you add a duplicate, it is simply ignored. Think of it as a mathematical set: no repeats allowed.
Map Core API
Set Core API
Object vs Map
| Object {} | Map | |
|---|---|---|
| Key types | Strings & Symbols only | Any value |
| Order | Not fully guaranteed | Insertion order |
| Size | Object.keys(o).length | map.size |
| Iteration | for...in (includes prototype) | for...of / forEach |
| Performance | Slower for frequent add/delete | Optimized |
| Default keys | Has prototype keys | None |
Iterating Map & Set
How to Apply Map & Set
Example: Word Frequency Counter
Count how many times each word appears in a sentence. A Map is ideal because we need string keys → number values.
Example: Deduplicate an Array
Remove duplicate values from an array in one line using a Set.
Example: Object Keys in a Map
Map's real power shines when you need non-string keys. Here we store metadata about DOM elements:
Constructing from Iterables
Common Mistakes
Map vs Set Summary
| Map | Set | |
|---|---|---|
| Stores | Key-value pairs | Unique values |
| Add | .set(key, val) | .add(val) |
| Read | .get(key) | .has(val) |
| Check | .has(key) | .has(val) |
| Remove | .delete(key) | .delete(val) |
| Count | .size | .size |
| Best for | Lookups, caches, metadata | Dedup, membership, tags |
Question 1 of 5
What does new Set([1, 2, 2, 3, 3, 3]) contain?
Question 2 of 5
Which method adds a key-value pair to a Map?
Question 3 of 5
What is the main advantage of Map over a plain object for storing key-value data?
Question 4 of 5
What does the following code output?
Question 5 of 5
Which line correctly removes all entries from a Map called cache?