ES6+ (Modern JavaScript) · Structure

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.

Intermediate 5 min Lesson 16 of 23 Runnable examples
0/23 in ES6+
On this page · 5 min · Intermediate

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#

JavaScript Illustrative
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#

JavaScriptCounting, object keys and set maths Runnable
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)));
Expected output
[ [ '/home', 3 ], [ '/cart', 1 ] ]
3 2
10:30
[ 'js' ]
[ 'js', 'css', 'html', 'react' ]
{"/home":3,"/cart":1}
Opens this example in the full playground

Step-by-step explanation#

  1. Each page visit increments its counter; ?? 0 starts new pages at zero.
  2. Spreading the Map shows [key, value] pairs in insertion order.
  3. The user object itself is the key — impossible with a plain object (keys become strings).
  4. Intersection keeps items of a that are also in b.
  5. Union spreads both into a new Set to drop duplicates.
  6. 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#

Using map[key] instead of get/set

visits['/home'] = 1 sets a normal property on the Map object, not an entry. Always use .set() and .get().

JSON.stringify(map)

It outputs {}. Convert first: JSON.stringify(Object.fromEntries(map)) or [...map].

Expecting Set to dedupe objects by content

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?
Count with a Map, then spread it and sort by count.
Show solution
JavaScript Runnable
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 ]
Opens this example in the full playground

Mini quiz#

Map and Set quizMultiple choice Question 1 of 3

Which can use an object as a key while keeping it as an object?

Score so far: 0/0

Want more? Practise all ES6+ MCQs · ES6+ interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.