JavaScript
Intermediate
Language Basics
· 6 min read
JavaScript Map and Set
Lesson 27 of 38 in the JavaScript learning path.
When should I use Map or Set instead of a plain object?
Map stores any key and remembers insertion order. Set stores unique values.
Objects coerce keys to strings. A Map can key a lesson by its numeric id without that surprise.
Syntax & Parameters
const byId = new Map(); byId.set(lesson.id, lesson);
Example
Interactive preview availableconst lessons = [
{ id: 4, title: "Routes" },
{ id: 9, title: "Queries" },
{ id: 4, title: "Routes again" }
];
const byId = new Map();
const seen = new Set();
for (const lesson of lessons) {
if (seen.has(lesson.id)) continue;
seen.add(lesson.id);
byId.set(lesson.id, lesson);
}
const list = document.querySelector("#out");
for (const lesson of byId.values()) {
const item = document.createElement("li");
item.textContent = lesson.id + " " + lesson.title;
list.append(item);
}
Expected Output
Two list items: 4 Routes and 9 Queries. The duplicate Routes row is skipped.
Line-by-Line Walkthrough
- The array has a duplicate id 4.
- Map will hold one lesson per id.
- Set records ids already kept.
- The loop skips an id that is already in the set.
- set stores the first lesson object.
- values() walks insertion order.
- The list renders text, not HTML.
- A plain object would also stringify ids, but Set makes the uniqueness obvious.
Common Pitfalls & Security
Map and Set are not JSON.
- JSON.stringify on a Map yields an empty object unless you convert it first.
- Set has checks SameValueZero. NaN is treated as already present.
- Objects as keys work in Map and confuse people who expect deep equality.
- Forgetting to skip duplicates still lets the second set() overwrite the first.
Best Practices & Modern Standards
Use Set when you only need uniqueness. Use Map when you need the value too.
Convert to an array with Array.from before you send JSON.
Real-World Use
The roster builder drops a student who was scanned twice and keeps the first enrollment for that id.
Frequently Asked Questions
Why not an object?
Object keys become strings. Map keeps a number as a number.
Does Set preserve order?
Yes. Insertion order is part of the spec.
How do I empty one?
Call clear().
Can I store objects in a Set?
Yes. Equality is by reference, not by deep compare.