Maps and Sets

Topic 1 of 3 in Built-in objects6 min readBeginnerFree course

Overview

Objects and arrays cover most needs, but two built-in collections solve common problems more cleanly:

  • A Set is a collection of unique values. Add the same value twice and it’s stored once.
  • A Map is a collection of key–value pairs, like an object, but its keys can be anything — numbers, objects, functions, DOM elements.

A Set built from ‘web’, ‘js’, ‘web’ keeps only ‘web’ and ‘js’, ignoring the duplicate. A Map links keys of any type — the string ‘/home’, the number 42, and a button element object — to values.

Set — unique values

JavaScript
const tags = new Set(['web', 'js', 'web']);
tags.size;          // 2
tags.has('js');     // true
tags.add('css');    // returns the set, so calls can be chained
tags.delete('web'); // true if it was there
tags.clear();       // removes everything

for (const tag of tags) console.log(tag);

Removing duplicates from an array is a one-liner:

JavaScript
const unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]

Why use a Set?

set.has(x) is very fast however many items there are, whereas array.includes(x) checks items one by one. When you check membership often — “has this user already voted?”, “have we seen this URL?” — a Set is the right tool:

JavaScript
const seen = new Set();
for (const url of urls) {
  if (seen.has(url)) continue; // skip repeats
  seen.add(url);
  crawl(url);
}

Set operations

Modern browsers include methods for combining sets:

JavaScript
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);

a.union(b);         // Set {1, 2, 3, 4}
a.intersection(b);  // Set {2, 3}
a.difference(b);    // Set {1}
a.isSubsetOf(b);    // false

In older environments you can do the same with spread and filter: new Set([...a].filter((x) => b.has(x))) is the intersection.

Map — key–value pairs

JavaScript
const visits = new Map();
visits.set('/home', 10);
visits.set('/courses', 4);

visits.get('/home');   // 10
visits.get('/about');  // undefined
visits.has('/about');  // false
visits.size;           // 2
visits.delete('/courses');

for (const [page, count] of visits) {
  console.log(page, count);
}

You can create a Map from an array of pairs — and from an object, via Object.entries:

JavaScript
const prices = new Map([['tea', 20], ['coffee', 35]]);
const fromObject = new Map(Object.entries({ tea: 20, coffee: 35 }));
const backToObject = Object.fromEntries(prices); // { tea: 20, coffee: 35 }

keys(), values() and entries() give you iterators, which you can spread into arrays:

JavaScript
[...prices.keys()];   // ['tea', 'coffee']
[...prices.values()]; // [20, 35]

Objects as keys

This is something plain objects can’t do — their keys are always turned into strings:

JavaScript
const user1 = { name: 'Asha' };
const user2 = { name: 'Ravi' };

const scores = new Map();
scores.set(user1, 90);
scores.set(user2, 75);
scores.get(user1); // 90

const obj = {};
obj[user1] = 90;   // key becomes the string '[object Object]'
obj[user2] = 75;   // overwrites it!

Keys are matched by identity, like ===. A new object that merely looks the same is a different key: scores.get({ name: 'Asha' }) is undefined.

Map or object?

Use a Map when keys aren’t simple strings (for example, DOM elements or objects), when you add and remove keys often, or when you need the size quickly. Use a plain object for fixed, known fields like a user record.

Plain object Map
Key types strings and symbols anything
Size Object.keys(obj).length map.size
Order mostly insertion (number-like keys first) always insertion order
Looping Object.entries(obj) for…of map directly
JSON works directly convert with Object.fromEntries first
Best for records with known fields dynamic lookups and caches

WeakMap and WeakSet hold objects without stopping them from being garbage-collected — handy for caching data about DOM elements.

JavaScript
const clickCounts = new WeakMap();
button.addEventListener('click', () => {
  clickCounts.set(button, (clickCounts.get(button) ?? 0) + 1);
});
// If the button is removed from the page, its entry can be cleaned up automatically.

WeakMaps only accept objects as keys and can’t be looped over or sized — the trade-off for not keeping things alive.

Exercise

Remove duplicates

Write unique(list) that returns a new array without duplicate values, keeping the first occurrence order. Then write countBy(list) that returns a Map of each value to how many times it appears.

JavaScript
function unique(list) {
  // your code here
}

function countBy(list) {
  // your code here
}

countBy(['a', 'b', 'a']); // Map { 'a' => 2, 'b' => 1 }

Summary

  • A Set stores each value once; has checks membership quickly.
  • A Map stores key–value pairs and allows any value — even objects — as a key.
  • Both keep insertion order, have a size, and work with for…of and spread.
  • Values are compared like === (with NaN equal to itself), so two look-alike objects are different keys.
  • Use a plain object for fixed records, a Map for dynamic lookups.