JavaScript Map and Set: When to Use Them
Map and Set are keyed collections with real advantages over objects and arrays. Learn the API, the differences, and when they win.
By Velloreth
Map
A keyed collection where keys can be any type.
const map = new Map();
map.set('name', 'Ada');
map.set(42, 'the answer');
map.set({ id: 1 }, 'object key');
map.get('name'); // 'Ada'
map.has(42); // true
map.size; // 3
Why not an object
An object’s keys are strings or symbols. A Map’s keys can be anything.
const obj = {};
obj[42] = 'value';
Object.keys(obj); // ['42'] — the number became a string
const map = new Map();
map.set(42, 'value');
[...map.keys()]; // [42] — still a number
The other differences:
| Object | Map | |
|---|---|---|
| Key types | String, symbol | Any |
| Size | Object.keys(o).length | map.size |
| Iteration | Object.entries | Directly iterable |
| Prototype keys | Inherited keys possible | None |
| JSON | JSON.stringify works | Needs conversion |
| Order | Integer keys first | Insertion order |
The API
map.set(key, value); // add or update
map.get(key); // read, undefined if missing
map.has(key); // boolean
map.delete(key); // remove, returns boolean
map.clear(); // remove all
map.size; // number of entries
Iteration
for (const [key, value] of map) { }
map.keys(); // iterator of keys
map.values(); // iterator of values
map.entries(); // iterator of [key, value]
map.forEach((value, key) => { });
Note the argument order in forEach: value first, then key. This is the opposite of what people expect, and it differs from Array.prototype.forEach.
Converting
// Map to array
const entries = [...map]; // [[k, v], ...]
const keys = [...map.keys()];
const values = [...map.values()];
// Array to Map
const map = new Map([['a', 1], ['b', 2]]);
// Map to object
const obj = Object.fromEntries(map);
// Object to Map
const map2 = new Map(Object.entries(obj));
Counting occurrences
A classic use case.
const counts = new Map();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
Caching
const cache = new Map();
function expensive(key) {
if (cache.has(key)) return cache.get(key);
const result = compute(key);
cache.set(key, result);
return result;
}
A Map is a good cache because it preserves insertion order, which makes it easy to evict the oldest entry.
if (cache.size > 100) {
const oldest = cache.keys().next().value;
cache.delete(oldest);
}
Set
A collection of unique values.
const set = new Set([1, 2, 2, 3, 3]);
set.size; // 3
Deduplicating
The most common use.
const unique = [...new Set([1, 2, 2, 3, 3])]; // [1, 2, 3]
The API
set.add(value); // add, returns the set
set.has(value); // boolean, O(1)
set.delete(value); // remove, returns boolean
set.clear(); // remove all
set.size; // number of values
Membership checks
Set.has is O(1) on average, while Array.includes is O(n).
// Slow for repeated checks
const allowed = ['a', 'b', 'c'];
items.filter((i) => allowed.includes(i)); // O(n*m)
// Fast
const allowedSet = new Set(['a', 'b', 'c']);
items.filter((i) => allowedSet.has(i)); // O(n)
For a small list it does not matter. For a list of thousands checked repeatedly, it is a large difference.
Set operations
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
// Union
const union = new Set([...a, ...b]); // {1, 2, 3, 4}
// Intersection
const intersection = new Set([...a].filter((x) => b.has(x))); // {2, 3}
// Difference
const difference = new Set([...a].filter((x) => !b.has(x))); // {1}
// Symmetric difference
const symmetric = new Set([
...[...a].filter((x) => !b.has(x)),
...[...b].filter((x) => !a.has(x)),
]); // {1, 4}
Modern engines also support the methods directly: a.union(b), a.intersection(b), a.difference(b), a.symmetricDifference(b), plus isSubsetOf and isSupersetOf.
Iteration
for (const value of set) { }
set.forEach((value) => { });
[...set];
WeakMap and WeakSet
The weak variants hold their keys weakly, so entries are removed when the key object is garbage collected.
const privateData = new WeakMap();
class User {
constructor(name) {
privateData.set(this, { name });
}
getName() {
return privateData.get(this).name;
}
}
The constraints:
- Keys must be objects. Primitives are not allowed.
- Not iterable. There is no
size, nokeys(), noforEach. - Not clearable. Entries disappear when the key is collected.
The use case is attaching data to an object without preventing its collection, and without exposing the data as a property. This is how private class fields were emulated before #private syntax.
When to use which
Use a Map when:
- Keys are not strings (objects, numbers, functions).
- You add and delete entries frequently.
- You need the size.
- You need guaranteed insertion order.
- You are building a cache or a lookup table.
Use an object when:
- The shape is fixed and known.
- You serialise to JSON.
- You use it as a record with named fields.
- You want destructuring and spread.
Use a Set when:
- You need unique values.
- You check membership repeatedly.
- You need set operations.
Use an array when:
- Order matters and duplicates are allowed.
- You need index access.
- You use array methods heavily.
Gotchas
Map keys are compared by reference for objects.
const map = new Map();
map.set({ id: 1 }, 'a');
map.get({ id: 1 }); // undefined — different object
Two objects with the same content are different keys. This is a common surprise.
NaN is a valid Map key and Set value.
const set = new Set([NaN, NaN]);
set.size; // 1 — SameValueZero treats them as equal
Set does not deduplicate objects by content.
new Set([{ a: 1 }, { a: 1 }]).size; // 2 — different references
JSON.stringify does not serialise a Map or Set.
JSON.stringify(new Map([['a', 1]])); // '{}'
JSON.stringify(new Set([1, 2])); // '{}'
Convert first: JSON.stringify([...map]) or Object.fromEntries(map).
Map.forEach argument order is (value, key). The reverse of what you might expect.
Performance characteristics
Map and Set are hash-based, so the common operations are O(1) on average.
| Operation | Array | Object | Map | Set |
|---|---|---|---|---|
| Lookup by key | O(n) | O(1) | O(1) | O(1) |
| Insert | O(1) | O(1) | O(1) | O(1) |
| Delete | O(n) | O(1) | O(1) | O(1) |
| Has | O(n) | O(1) | O(1) | O(1) |
| Size | O(1) | O(n) | O(1) | O(1) |
The practical implications:
Repeated membership checks. Converting an array to a Set turns an O(n) check into O(1). For a filter over a large list, this is the difference between seconds and milliseconds.
// O(n * m)
items.filter((i) => allowed.includes(i));
// O(n)
const allowedSet = new Set(allowed);
items.filter((i) => allowedSet.has(i));
Frequent deletion. Deleting from an array with splice is O(n) because the remaining elements shift. Deleting from a Map or Set is O(1).
Size checks. Object.keys(obj).length allocates an array. map.size is a property read.
The caveat: for small collections, the constant factors dominate and the difference is invisible. Optimise when the profiler shows it matters.
Choosing between them
A decision guide for the common cases.
A record with known fields — a plain object. It destructures, spreads, and serialises to JSON.
const user = { id: 1, name: 'Ada' };
A lookup table with dynamic keys — a Map. It handles non-string keys and has a size.
const byId = new Map();
byId.set(user.id, user);
A collection of unique values — a Set.
const tags = new Set(['js', 'css']);
An ordered list with duplicates — an array.
const log = ['started', 'started', 'finished'];
A cache with eviction — a Map, because it preserves insertion order.
const cache = new Map();
The most common mistake is using an object as a dictionary with dynamic keys. A Map is usually the better choice, because it avoids prototype pollution, handles any key type, and reports its size directly.
Practical guidance
- Use a Map for non-string keys and frequent add/delete.
- Use a Set to deduplicate and for fast membership checks.
- Use
[...new Set(arr)]for the dedupe idiom. - Convert before serialising to JSON.
- Remember object keys compare by reference.
- Use a WeakMap for private data attached to objects.
- Prefer a plain object for fixed-shape records.
- Use
Object.fromEntriesto convert a Map to an object.
For the related guides, see javascript-object-methods-guide and javascript-array-methods-guide. For the broader context, hash-tables-explained and data-structures-every-developer-should-know.
Quotable summary
A Map allows keys of any type and preserves insertion order, unlike a plain object whose keys are strings or symbols, and it has a size property where an object needs Object.keys(obj).length. A Set stores unique values and is the fastest way to deduplicate an array, with O(1) membership checks compared to the O(n) of Array.includes. Both are iterable, so they work directly with for…of and spread, and Object.fromEntries converts a Map to a plain object. Use a Map for frequent additions and deletions and for non-string keys, and a plain object for fixed-shape records that get serialised to JSON, since JSON.stringify does not serialise a Map or Set. Remember that object keys compare by reference, so two objects with the same content are different keys.