Maps and Sets
A Set stores unique values with no duplicates; a Map stores key-value pairs with keys of any type and fast lookup.
Loading visual…
Definition
A `Set` is a collection of unique values. Adding a value that already exists is a no-op, `set.add(x)` twice still leaves one `x`, which makes Sets a natural way to deduplicate data or track membership. Values are compared the way `===` does, with the special case that `NaN` is considered equal to itself, and the collection remembers insertion order when you iterate it. A `Map` is a collection of key-value pairs, similar to a plain object, but with two practical advantages: any value can be a key, not just strings and symbols, so objects, functions, or numbers all work as keys directly; and a Map preserves insertion order and reports its size directly through `map.size`. Both `Map` and `Set` offer `O(1)` average-time lookup, `map.get(key)` or `set.has(value)`, because they are backed by a hash table rather than requiring a scan, which is what makes them faster than an array's `includes` or `find` for membership checks on larger collections.
Examples
const seen = new Set();
seen.add("a");
seen.add("a");
seen.add("b");
// seen has 2 values: "a", "b"Adding a value that is already in the Set changes nothing; a Set never holds duplicates.
const scores = new Map();
scores.set("ada", 90);
scores.set("grace", 95);
scores.get("grace"); // 95
scores.has("linus"); // falseget and has look a key up directly in the hash table, an O(1) operation on average regardless of how many entries the Map holds.
const unique = [...new Set([1, 2, 2, 3, 1])];
// [1, 2, 3]Spreading a Set built from an array back into an array is a common one-line way to deduplicate a list.
Common mistakes
- Using a plain object as a Map replacement and expecting non-string keys to stay distinct; object keys get coerced to strings.
- Assuming a Set collapses duplicate-looking objects; each distinct object reference is still added as a separate entry.
- Iterating a Map like an array and forgetting entries come back as `[key, value]` pairs, not plain values.
Key takeaways
- A Set stores unique values; adding a duplicate value does nothing.
- A Map accepts any value as a key and preserves insertion order.
- Both Map and Set give average O(1) lookup, unlike scanning an array with includes or find.
`const set = new Set(); set.add({}); set.add({});` What is `set.size`?
Where you see this
- Deduplicating an array of ids or tags while preserving their original order.
- Tracking which items have already been processed in a loop to avoid doing the work twice.
- Building a fast lookup table from an array of records, keyed by id, instead of calling find repeatedly.
- Using non-string keys, like DOM nodes or objects, as lookup keys in a Map when a plain object cannot express that.