When should you use Set or Map?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
Use a Set when you need a collection of unique values, and a Map when you need key-value pairs — especially if the keys are not strings.
const tags = new Set(["js", "css", "js"]);
tags.size; // 2 — duplicates dropped automatically
tags.has("js"); // true
tags.add("html");
tags.delete("css");
const meta = new Map();
meta.set(userObject, { lastSeen: Date.now() }); // an object as a key
meta.get(userObject);
meta.size;
Set instead of an array
has() is roughly constant time, while array.includes() scans. For a membership check inside a loop over thousands of items, that is the difference between fast and quadratic:
const blocked = new Set(blockedIds); // build once
items.filter((i) => !blocked.has(i.id)); // fast lookups
Map instead of a plain object
| Object | Map | |
|---|---|---|
| Key types | String and Symbol only | Anything, including objects |
| Size | Object.keys(o).length | map.size |
| Order | Integer-like keys sort first | Strict insertion order |
| Inherited keys | Has toString etc. on the prototype | None |
| Iteration | Needs Object.entries | Directly iterable |
The prototype row matters for safety: a user-supplied key such as __proto__ can misbehave on an object, while a Map treats it as an ordinary key. Use a Map whenever keys come from outside.
What they do not do
Both compare objects by reference, so two identical-looking literals are two entries. Neither serialises with JSON.stringify — you get {}, so convert with [...set] or Object.fromEntries(map) first.
The weak variants
WeakMap and WeakSet hold keys weakly, so an entry disappears once nothing else references the key. That makes them the right choice for attaching metadata to DOM nodes or objects you do not own, without leaking memory. They are not iterable and have no size, by design.
