Skip to content
  • Map & Set · JavaScript

Map & Set

LearnViaNotes @learnvianotes· 2 min read

Map is a key → value store where keys can be anything; Set is a collection of unique values. Both keep insertion order and have O(1) average lookups.

Map

JavaScript
const m = new Map();
const objKey = { id: 1 };
m.set("name", "Asha").set(42, "number key").set(objKey, "object key");
console.log(m.get(objKey), m.get(42), m.get("missing"));
console.log(m.has("name"), m.size);
m.delete(42);
console.log(m);
for (const [key, value] of m) console.log(key, "→", value);
console.log([...m.keys()], new Map(Object.entries({ a: 1 })));
Output
object key number key undefined
true 3
Map(2) { 'name' => 'Asha', { id: 1 } => 'object key' }
name → Asha
{ id: 1 } → object key
[ 'name', { id: 1 } ] Map(1) { 'a' => 1 }

Map vs plain object

ObjectMap
Key typesStrings and symbols (others are stringified)Any value — objects, functions, NaN
OrderInteger keys first, then insertionPure insertion order
SizeObject.keys(o).lengthm.size
IterationVia Object.entriesDirectly iterable
Accidental keysInherits toString, constructor, __proto__ risksNone
Frequent add/deleteSlowerOptimised for it
JSON supportNativeConvert: Object.fromEntries(m)

Set

JavaScript
const s = new Set([3, 1, 3, 2, 1]);
s.add(4).add(1);
console.log(s, s.size, s.has(2));
s.delete(3);
console.log([...s]);
console.log([...new Set("mississippi")].join(""));
Output
Set(4) { 3, 1, 2, 4 } 4 true
[ 1, 2, 4 ]
misp

Set operations (ES2025, Node 22+)

JavaScript
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
console.log(a.union(b));
console.log(a.intersection(b));
console.log(a.difference(b), a.symmetricDifference(b));
console.log(new Set([3]).isSubsetOf(a), a.isDisjointFrom(new Set([9])));
// the classic way, still common in interviews:
console.log([...a].filter((x) => b.has(x)));
Output
Set(5) { 1, 2, 3, 4, 5 }
Set(2) { 3, 4 }
Set(2) { 1, 2 } Set(3) { 1, 2, 5 }
true true
[ 3, 4 ]

Equality of keys

JavaScript
const s = new Set([NaN, NaN, 0, -0, {}, {}]);
console.log(s.size);             // NaN once, 0/-0 once, two distinct objects
const m = new Map([[[1], "a"]]);
console.log(m.get([1]));         // a different array → different key
Output
4
undefined

When would you use a Map instead of an object?

How do you remove duplicates from an array?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report