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

Syntax
const byId = new Map(); byId.set(lesson.id, lesson);

Example

Interactive preview available
app.js
const 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

  1. The array has a duplicate id 4.
  2. Map will hold one lesson per id.
  3. Set records ids already kept.
  4. The loop skips an id that is already in the set.
  5. set stores the first lesson object.
  6. values() walks insertion order.
  7. The list renders text, not HTML.
  8. 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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…