CPCODELAB
JavaScript

Sets and Maps

8 min read

Set

A Set is a collection of unique values of any type. Adding a duplicate has no effect. Sets are iterable and maintain insertion order.

javascript
const tags = new Set(["js", "css", "js", "html"]);
tags.size;          // 3 (duplicate removed)
tags.has("js");     // true
tags.add("react");
tags.delete("css");

for (const tag of tags) console.log(tag);

// Deduplication trick
const unique = [...new Set([1, 2, 2, 3, 3, 3])];
// [1, 2, 3]

Map

A Map is a key-value store where keys can be any type (not just strings). Unlike plain objects, Maps maintain insertion order and have a reliable .size property.

javascript
const cache = new Map();
cache.set("user:1", { name: "Alice" });
cache.set(42, "answer");
cache.set(true, "boolean key!");

cache.get("user:1"); // { name: "Alice" }
cache.has(42);       // true
cache.size;          // 3
cache.delete(42);
cache.clear();

// Iterate
for (const [key, value] of cache) {
  console.log(key, value);
}

Use Map over plain objects when keys are not strings, when key-order matters, or when you need frequent additions and deletions — Maps have better performance for those use cases.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises