01 / 20

Map & Set
in JavaScript

Master key-value storage with Map and unique membership with Set: two powerful built-in data structures that go beyond plain objects and arrays.

JavaScript

Why Go Beyond Objects & Arrays?

Plain objects ({}) and arrays ([]) are everywhere in JavaScript, but they have limits. Objects only accept string or Symbol keys, and arrays don't enforce uniqueness. Map and Set solve these problems with purpose-built APIs.

Map
Any value as a key: objects, numbers, functions. Maintains insertion order.
Set
Stores only unique values. Perfect for membership checks and deduplication.

What Is a Map?

A Map is an ordered collection of key-value pairs where keys can be any type: strings, numbers, objects, or even other Maps.

Map "name" → "Alice" 42 → "the answer" {obj} → [1, 2, 3] KEYS (any type) VALUES (any type)

What Is a Set?

A Set is an ordered collection of unique values. If you add a duplicate, it is simply ignored. Think of it as a mathematical set: no repeats allowed.

Set "apple" 42 true {obj} null ✕ "apple" rejected: already exists

Map Core API

// Create a Map const users = new Map(); // Set key-value pairs users.set("alice", { age: 30 }); users.set("bob", { age: 25 }); // Read a value users.get("alice"); // { age: 30 } // Check existence users.has("bob"); // true // Remove & count users.delete("bob"); users.size; // 1

Set Core API

// Create a Set const tags = new Set(); // Add values (duplicates ignored) tags.add("js"); tags.add("css"); tags.add("js"); // ignored! // Check membership tags.has("js"); // true // Remove & count tags.delete("css"); tags.size; // 1 // Clear everything tags.clear(); tags.size; // 0

Object vs Map

Object {} Map
Key types Strings & Symbols only Any value
Order Not fully guaranteed Insertion order
Size Object.keys(o).length map.size
Iteration for...in (includes prototype) for...of / forEach
Performance Slower for frequent add/delete Optimized
Default keys Has prototype keys None

Iterating Map & Set

// Map iteration const m = new Map([["a", 1], ["b", 2]]); for (const [key, val] of m) { console.log(key, val); // "a" 1, "b" 2 } m.forEach((val, key) => { console.log(key, val); }); // Set iteration const s = new Set([10, 20, 30]); for (const item of s) { console.log(item); // 10, 20, 30 }

How to Apply Map & Set

1
Identify the need. Do you need key-value lookup (Map) or uniqueness checks (Set)?
2
Construct with new. Use new Map() or new Set(). Optionally pass an iterable of entries.
3
Add data. Map: .set(key, value). Set: .add(value).
4
Query data. Map: .get(key), .has(key). Set: .has(value).
5
Remove data. Both: .delete() or .clear().

Example: Word Frequency Counter

Count how many times each word appears in a sentence. A Map is ideal because we need string keys → number values.

function wordCount(sentence) { const freq = new Map(); for (const word of sentence.split(" ")) { const count = freq.get(word) || 0; freq.set(word, count + 1); } return freq; } const result = wordCount("the cat sat on the mat"); // Map { "the" → 2, "cat" → 1, "sat" → 1, // "on" → 1, "mat" → 1 }

Example: Deduplicate an Array

Remove duplicate values from an array in one line using a Set.

const nums = [1, 3, 5, 3, 1, 7, 5]; const unique = [...new Set(nums)]; // [1, 3, 5, 7] // Works with strings too const words = ["hi", "bye", "hi", "hello"]; const uniqueWords = [...new Set(words)]; // ["hi", "bye", "hello"]

Example: Object Keys in a Map

Map's real power shines when you need non-string keys. Here we store metadata about DOM elements:

const metadata = new Map(); const btn1 = document.querySelector("#save"); const btn2 = document.querySelector("#cancel"); metadata.set(btn1, { clicks: 0, label: "Save" }); metadata.set(btn2, { clicks: 0, label: "Cancel" }); btn1.addEventListener("click", () => { const data = metadata.get(btn1); data.clicks++; });

Constructing from Iterables

// Map from array of [key, value] pairs const m = new Map([ ["x", 10], ["y", 20], ["z", 30] ]); // Set from any iterable const s = new Set("hello"); // Set { "h", "e", "l", "o" } (auto-deduped!) // Convert Map back to Object const obj = Object.fromEntries(m); // { x: 10, y: 20, z: 30 } // Convert Object to Map const m2 = new Map(Object.entries(obj));

Common Mistakes

✕ Using bracket syntax on Map
map["key"] = val treats Map as an object, bypassing its API. Use .set() and .get().
✕ Expecting Set index access
set[0] is undefined. Sets have no index. Convert to array first: [...set][0].
✕ Object reference traps
Two identical-looking objects are different keys: {a:1} !== {a:1}. Map uses reference equality for objects.

Map vs Set Summary

Map Set
Stores Key-value pairs Unique values
Add .set(key, val) .add(val)
Read .get(key) .has(val)
Check .has(key) .has(val)
Remove .delete(key) .delete(val)
Count .size .size
Best for Lookups, caches, metadata Dedup, membership, tags

Question 1 of 5

What does new Set([1, 2, 2, 3, 3, 3]) contain?

Question 2 of 5

Which method adds a key-value pair to a Map?

Question 3 of 5

What is the main advantage of Map over a plain object for storing key-value data?

Question 4 of 5

What does the following code output?

const s = new Set(); s.add("a"); s.add("b"); s.add("a"); console.log(s.size);

Question 5 of 5

Which line correctly removes all entries from a Map called cache?