Map and Set
Map and Set are purpose-built collections. Knowing when to pick them over a plain object or array is a sign of an experienced developer.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Syntax
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 28, 2026
Related tutorials
Learning objectives#
- Choose Map vs object and Set vs array
- Count and group with a Map
- Use objects as Map keys
- Do union, intersection and difference with Sets
- Convert between Map, object and array
Explanation#
Map: key → value pairs where keys can be anything (objects, numbers, functions). It keeps insertion order, has .size, and is fast for frequent adds and deletes.
Use a plain object for fixed-shape records ({ name, age }) and JSON data. Use a Map for dynamic lookups, counters and caches.
Set: a collection of unique values. .has() is very fast, much faster than array.includes() on large lists.
Conversions: [...map] or [...set] → arrays; new Map(Object.entries(obj)) and Object.fromEntries(map) → between Map and object.
WeakMap/WeakSet hold object keys “weakly”, so entries disappear when the object is garbage-collected — ideal for attaching data to DOM nodes without leaks.
Syntax#
const m = new Map([['a', 1]]);
m.set('b', 2).get('a'); // 1
const s = new Set([1, 2, 2]); // Set { 1, 2 }
s.has(2); // true
Code example: Counting, object keys and set maths#
const visits = new Map();
for (const page of ['/home', '/cart', '/home', '/home']) {
visits.set(page, (visits.get(page) ?? 0) + 1);
}
console.log([...visits]);
console.log(visits.get('/home'), visits.size);
const user = { id: 1 };
const lastSeen = new Map([[user, '10:30']]); // an object as a key
console.log(lastSeen.get(user));
const a = new Set(['js', 'css', 'html']);
const b = new Set(['js', 'react']);
console.log([...a].filter(x => b.has(x))); // intersection
console.log([...new Set([...a, ...b])]); // union
console.log(JSON.stringify(Object.fromEntries(visits)));
[ [ '/home', 3 ], [ '/cart', 1 ] ]
3 2
10:30
[ 'js' ]
[ 'js', 'css', 'html', 'react' ]
{"/home":3,"/cart":1}Step-by-step explanation#
- Each page visit increments its counter; ?? 0 starts new pages at zero.
- Spreading the Map shows [key, value] pairs in insertion order.
- The user object itself is the key — impossible with a plain object (keys become strings).
- Intersection keeps items of a that are also in b.
- Union spreads both into a new Set to drop duplicates.
- Object.fromEntries converts the Map into a plain object, which JSON.stringify can then send to a server.
Real-world use case#
Counting word frequencies, caching API responses by URL, tracking selected IDs in a UI (Set), and de-duplicating tags.
Common mistakes#
visits['/home'] = 1 sets a normal property on the Map object, not an entry. Always use .set() and .get().
It outputs {}. Convert first: JSON.stringify(Object.fromEntries(map)) or [...map].
new Set([{ a: 1 }, { a: 1 }]) has 2 items — they are different objects. Dedupe by an id instead.
Best practices#
- Map for dynamic keys and frequent changes; object for records
- Set for uniqueness and fast membership checks
- Convert to plain data before JSON
- Use WeakMap for metadata about objects you do not own
Remember this#
Map = dictionary with any kind of key. Set = guest list with no duplicates.
get/set/has/delete/size — same verbs for both.
Map → JSON? Object.fromEntries(map) first.
Practice exercise#
Your task: Given words = ["a", "b", "a", "c", "b", "a"], build a Map of word counts and print the most frequent word.
Need a hint?
Show solution
const words = ['a', 'b', 'a', 'c', 'b', 'a'];
const counts = new Map();
for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
const [top] = [...counts].sort((x, y) => y[1] - x[1]);
console.log(top); // [ 'a', 3 ]
Mini quiz#
Which can use an object as a key while keeping it as an object?
Want more? Practise all ES6+ MCQs · ES6+ interview questions
My notes#
Saved in this browser.