Skip to content

Set and Map

Collection types for unique values and key-value pairs with any key type, not just strings.

What you'll learn

  • Set: a collection of unique values
  • Map: key-value pairs where keys can be any type
  • Adding, checking, and removing entries
  • Iterating with for...of and spread
  • WeakSet and WeakMap for garbage-collectable keys

Concept

Why Not Just Objects and Arrays?

Plain objects only allow string and Symbol keys — using an object as a key silently converts it to "[object Object]". Arrays allow duplicates and have no fast "has this value?" check. Set and Map (ES6) solve these gaps: Set stores unique values of any type, and Map stores key-value pairs with keys of any type, preserving insertion order.

Set

A Set is a collection of unique values. add() inserts (duplicates are ignored), has() checks membership in O(1), delete() removes, and size gives the count. Sets are the clean way to deduplicate an array: [...new Set(arr)]. They preserve insertion order, so iteration is predictable.

Map

A Map is a collection of key-value pairs. Unlike objects, keys can be numbers, objects, functions, or even NaN. set(key, value), get(key), has(key), delete(key), and size are the core API. Use Map when you need a dictionary with non-string keys or when you need reliable insertion-order iteration (object key order has historical quirks).

Iteration

Both Set and Map are iterable with for...of. A Map yields [key, value] pairs. You can spread them into arrays or convert with Array.from(). Map also provides .keys(), .values(), and .entries() iterators. Neither has map or filter methods built in — convert to an array first or loop manually.

WeakSet and WeakMap

WeakMap and WeakSet hold weak references to keys: if the key object has no other references, it can be garbage-collected, and the entry disappears. This prevents memory leaks when associating data with DOM elements or other objects. Weak entries are not iterable and do not have size, because their contents can change at any time during GC. Use them for metadata attached to objects you do not own.

Choosing the Right Collection

Use an array for ordered, duplicate-allowing lists. Use a Set for uniqueness or fast membership checks. Use a plain object for string-keyed records with a known shape. Use a Map for dynamic dictionaries, non-string keys, or frequent add/remove with preserved order. Use WeakMap for private metadata on external objects.

Example

              // Set — deduplicate and check membership
const tags = new Set();
tags.add("js").add("web").add("js"); // duplicate ignored
console.log(tags.size); // 2
console.log(tags.has("web")); // true
tags.delete("js");
console.log([...tags]); // ["web"]

// Deduplicate an array in one line
const numbers = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(numbers)];
console.log("Unique:", unique); // [1, 2, 3, 4]

// Map — keys can be any type, even objects
const meta = new Map();
const userObj = { id: 1 };
meta.set(userObj, "admin");
meta.set("count", 42);
meta.set(100, "numeric key");
console.log(meta.get(userObj)); // "admin"
console.log(meta.get(100));    // "numeric key"
console.log(meta.size);        // 3

// Iterate a Map — yields [key, value] pairs
for (const [key, value] of meta) {
  console.log(key, "→", value);
}

// Convert Map to object (string keys only) and back
const strMap = new Map([["a", 1], ["b", 2]]);
const obj = Object.fromEntries(strMap);
console.log(obj); // { a: 1, b: 2 }
const backToMap = new Map(Object.entries(obj));

// WeakMap — metadata on DOM-like objects, GC-friendly
const privates = new WeakMap();
function setPrivate(obj, data) {
  privates.set(obj, data);
}
function getPrivate(obj) {
  return privates.get(obj);
}
const widget = {};
setPrivate(widget, { state: "hidden" });
console.log(getPrivate(widget)); // { state: "hidden" }
            

Shows Set deduplication and membership, Map with object and numeric keys, Map iteration, conversion between Map and Object with fromEntries/entries, and WeakMap for private metadata.

Try it

Common mistakes

The mistake

Using a plain object as a Map key and getting '[object Object]'

The fix

Object keys are coerced to strings, so two different objects become the same key '[object Object]'. Use a Map when you need object, number, or other non-string keys.

The mistake

Expecting Set and Map to have map and filter methods

The fix

Set and Map are iterable but do not have map/filter/reduce. Convert to an array first: [...set].map(fn), or use Array.from(map, fn). You can also loop with for...of and build a new collection manually.

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors