← All concepts
Data Structures, Operators & Strings

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"); // false

get 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.

Where you see this

Practice this

Further reading