SyntaxPilot
Courses/JavaScript/Lesson 21
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 21 of 40

Map and Set

queued

These are the notes for JavaScript episode 21. Arrays and objects quietly fail at two everyday jobs. Keeping things unique: removing repeat visitors with includes works for six names but takes over a second for 60,000, because includes reads every item. Looking things up by key: a word counter built on a plain object turns the word "constructor" into 'function Object() { [native code] }1', and using student objects as keys makes them all collide on "[object Object]". You'll invent the two collections built for these jobs: Set (each value once, instant has) and Map (keys of any type, no inherited keys, insertion order). Then you'll convert between objects, arrays, Maps, Sets and JSON, and learn which box to pick. Every output below is real Node.js 24 output (node main.js); timings will differ on your machine.

Builds on: loops and for...of (episode 6), arrays (7), objects (8), destructuring and spread (12), prototypes (17), JSON (19), Date.now() (20).

The real-life idea: the visitor register vs membership cards

A gym writes every visit on a new line of a register: Asha, Ravi, Asha, Meena, Ravi... To answer "how many different people came?" or "is Asha a member?", someone reads the whole register. So the gym switches to membership cards: one card per person in a box. Is Asha a member? Pull her card, instantly. A second card for Asha? Not allowed.

Gym JavaScript
The register: a line per visit an array (ordered, duplicates allowed)
Reading every line to check a name array.includes(x): checks every item
The card box: one card per person a Set
Pulling a card set.has(x): instant
A key rack: any key, its tag hanging on it a Map

The problem: duplicates in an array

const visits = ["Asha", "Ravi", "Asha", "Meena", "Ravi", "Asha"];
const unique = [];
for (const name of visits) {
  if (!unique.includes(name)) unique.push(name);
}
console.log(unique, unique.length);
[ 'Asha', 'Ravi', 'Meena' ] 3

It works, but includes compares with every item, every time. Scale it up:

const big = [];
for (let i = 0; i < 60000; i++) big.push(i % 30000);
let t = Date.now();
const u1 = [];
for (const x of big) if (!u1.includes(x)) u1.push(x);
console.log("array + includes:", u1.length, Date.now() - t, "ms");
t = Date.now();
const u2 = new Set(big);
console.log("Set:", u2.size, Date.now() - t, "ms");
array + includes: 30000 1094 ms
Set: 30000 3 ms

Same answer, hundreds of times faster. With n items, the array way does about n × n / 2 comparisons (it gets 4× slower each time the data doubles); the Set does about n steps.

Why: an array is a list, built to keep things in order and reach them by position. It is not built to answer "have I seen this before?".

The fix: Set

A Set is a collection where each value appears once.

const visitors = new Set();
visitors.add("Asha");
visitors.add("Ravi");
visitors.add("Asha");
console.log(visitors, visitors.size);
console.log(visitors.has("Ravi"), visitors.has("Kabir"));
visitors.delete("Ravi");
for (const v of visitors) console.log("Hello", v);
const visits = ["Asha", "Ravi", "Asha", "Meena", "Ravi", "Asha"];
console.log([...new Set(visits)]);
Set(2) { 'Asha', 'Ravi' } 2
true false
Hello Asha
[ 'Asha', 'Ravi', 'Meena' ]
Set What it does
new Set() / new Set(iterable) an empty Set / a Set of the unique values of an array, string, ...
.add(v) add a value (nothing happens if it's already there); returns the Set
.has(v) true/false, fast however big the Set is
.delete(v) remove; returns true if it was there
.size how many values (a property, not a method; not .length)
.clear() remove everything
for...of, .forEach visit values in insertion order
[...set], Array.from(set) back to an array
  • Dedupe in one line: [...new Set(array)], keeping first-seen order.
  • A Set has no positions: visitors[0] is undefined. Convert to an array if you need an index.
  • Why it's fast: inside, a Set is a hash table. It computes where a value would be stored and jumps straight there instead of scanning.
  • Node 22+ also has a.union(b), a.intersection(b), a.difference(b).
const a = new Set([1, 2, 3]), b = new Set([2, 3, 4]);
console.log(a.union(b), a.intersection(b), a.difference(b));
Set(4) { 1, 2, 3, 4 } Set(2) { 2, 3 } Set(1) { 1 }

Objects in a Set are compared by reference

const seen = new Set();
seen.add({ id: 1 });
seen.add({ id: 1 });
console.log(seen.size);
console.log(new Set([1, 1, "1"]));
2
Set(2) { 1, '1' }

Two objects that look the same are two different objects in memory. A Set compares like === (by reference for objects), not by contents. To dedupe objects, keep a Set of their ids: seenIds.has(user.id). The number 1 and the string "1" are different values.

The next problem: a plain object as a lookup table

Inherited keys break a word counter

const text = "the cat and the constructor of the toString";
const counts = {};
for (const word of text.split(" ")) {
  counts[word] = (counts[word] || 0) + 1;
}
console.log(counts);
{
  the: 3,
  cat: 1,
  and: 1,
  constructor: 'function Object() { [native code] }1',
  of: 1,
  toString: 'function toString() { [native code] }1'
}

Every plain object inherits properties from Object.prototype (episode 17), such as constructor and toString. So counts["constructor"] already existed: it was a function, and function + 1 joined text.

const counts = {};
console.log("constructor" in counts, Object.hasOwn(counts, "constructor"));
true false

Object keys become strings

const marks = {};
const asha = { name: "Asha" };
const ravi = { name: "Ravi" };
marks[asha] = 95;
marks[ravi] = 60;
console.log(marks[asha]);
console.log(Object.keys(marks));
60
[ '[object Object]' ]

Object keys are always strings (or symbols). Both students became the text "[object Object]", so Ravi overwrote Asha. Numbers are converted too: marks[1] and marks["1"] are the same key.

Why: a plain object is a record: named fields describing one thing, with text keys and inherited extras. Great for { name, score }; bad as a general lookup table.

The fix: Map

A Map stores key → value pairs, where the key can be any value: a string, a number, an object. It starts truly empty (no inherited keys), knows its size, and remembers insertion order.

const text = "the cat and the constructor of the toString";
const counts = new Map();
for (const word of text.split(" ")) {
  counts.set(word, (counts.get(word) || 0) + 1);
}
console.log(counts);
console.log(counts.get("the"), counts.size, counts.has("dog"));
Map(6) {
  'the' => 3,
  'cat' => 1,
  'and' => 1,
  'constructor' => 1,
  'of' => 1,
  'toString' => 1
}
3 6 false

Any type as a key, and looping

const asha = { name: "Asha" };
const ravi = { name: "Ravi" };
const marks = new Map();
marks.set(asha, 95).set(ravi, 60);
marks.set(1, "number one").set("1", "string one");
console.log(marks.get(asha), marks.get(ravi));
console.log(marks.get(1), marks.get("1"));
for (const [key, value] of marks) {
  console.log(key, "->", value);
}
95 60
number one string one
{ name: 'Asha' } -> 95
{ name: 'Ravi' } -> 60
1 -> number one
1 -> string one

(console.log prints the string "1" without quotes; it's still a different key from the number 1.)

Map What it does
new Map() / new Map([[k, v], ...]) empty / from key-value pairs
.set(k, v) add or replace; returns the Map, so calls chain
.get(k) the value, or undefined
.has(k) true/false
.delete(k), .clear() remove one / all
.size number of entries
for (const [k, v] of map) entries in insertion order
.keys(), .values(), .entries(), .forEach((v, k) => ...) other ways to walk it
const m = new Map([["a", 1], ["b", 2]]);
m.delete("a");
console.log(m.size, [...m.entries()], [...m.values()]);
m.forEach((value, key) => console.log(key, value));
m.clear();
console.log(m.size);
1 [ [ 'b', 2 ] ] [ 2 ]
b 2
0

The bracket mistake

const menu = new Map();
menu["chai"] = 20;
console.log(menu.get("chai"), menu.size);
menu.set("chai", 20);
console.log(menu.get("chai"), menu.size);
undefined 0
20 1

menu["chai"] = 20 puts a normal property on the Map object, not an entry in the map. Always use set and get.

Converting between objects, arrays, Maps, Sets and JSON

const prices = { chai: 20, samosa: 15, vada: 25 };
const menu = new Map(Object.entries(prices));
menu.set("lassi", 40);
console.log([...menu.keys()]);
console.log(JSON.stringify(menu));
console.log(JSON.stringify(Object.fromEntries(menu)));
const tags = new Set(["new", "hot"]);
console.log(JSON.stringify(tags), JSON.stringify([...tags]));
[ 'chai', 'samosa', 'vada', 'lassi' ]
{}
{"chai":20,"samosa":15,"vada":25,"lassi":40}
{} ["new","hot"]
From → to How
object → Map new Map(Object.entries(obj))
Map → object (string keys only) Object.fromEntries(map)
array → Set (dedupe) new Set(arr)
Set → array [...set] or Array.from(set)
Map → array of pairs [...map]
Map ↔ JSON JSON.stringify(Object.fromEntries(map)) or JSON.stringify([...map]) and back with new Map(...)

JSON.stringify of a Map or a Set is {}: JSON only knows objects and arrays (episode 19). Convert first.

Which one when?

Use When Example
Array an ordered list; duplicates fine; access by position quiz questions in order
Set every value unique; "have I seen this?" visitors, tags, seen questions
Object one thing with known, fixed fields; sending as JSON { name: "Asha", score: 7 }
Map a lookup table: counting, caching, grouping; keys that aren't strings; frequent adds/deletes word counts, marks by student object

Rule of thumb: unique → Set, lookup → Map, a record → object, an ordered list → array.

(You may also meet WeakMap and WeakSet: like Map and Set, but keys must be objects and don't keep them alive in memory. They're used for caches attached to objects; we'll see them in the performance episode.)

Common mistakes (and what really happens)

You wrote What happens Why Fix
if (!arr.includes(x)) arr.push(x) on 60,000 items about a second (minutes for millions) includes reads every item new Set(arr), set.has(x)
set.length, set[0] undefined, undefined a Set has size and no positions set.size, [...set][0]
set.add({ id: 1 }) twice size is 2 objects compare by reference a Set of ids
counts[word] = (counts[word] \|\| 0) + 1 constructor: 'function Object() { [native code] }1' objects inherit keys a Map (or Object.create(null))
marks[asha] = 95; marks[ravi] = 60 marks[asha] is 60; keys [ '[object Object]' ] object keys become strings marks.set(asha, 95)
menu["chai"] = 20 on a Map menu.get("chai") → undefined, size 0 brackets set a property, not an entry menu.set("chai", 20)
JSON.stringify(map) / (set) {} JSON has no Map or Set Object.fromEntries(map), [...set]
Math.max(map.values()) NaN an iterator isn't separate numbers Math.max(...map.values())

Mini project: the top 3 words in a paragraph

const paragraph = "Chai is life. Chai at the stall, chai at home, and chai with samosa at the stall.";
const counts = new Map();
for (const raw of paragraph.toLowerCase().split(/\s+/)) {
  const word = raw.replace(/[^a-z]/g, "");
  if (word) counts.set(word, (counts.get(word) || 0) + 1);
}
const top3 = [...counts].sort((a, b) => b[1] - a[1]).slice(0, 3);
for (const [word, n] of top3) console.log(word.padEnd(6), n);
console.log("Different words:", counts.size);
chai   4
at     3
the    2
Different words: 10

split(/\s+/) splits on any spaces and replace(/[^a-z]/g, "") strips punctuation (regular expressions are episode 23). [...counts] turns the Map into [word, count] pairs so they can be sorted.

Practice

  1. Find the items common to two shopping lists ["milk", "bread", "eggs", "tea"] and ["tea", "sugar", "milk"], and how many different items there are in total.
  2. Keep a Set of quiz questions a player has already seen, and a nextQuestion() that never repeats one (returns null when none are left).
  3. Save a Map chai → 20, samosa → 15 to JSON and load it back as a Map, in two different ways.
  4. Make a plain object safe as a counter for the word "constructor".
Solutions

1.

const mine = ["milk", "bread", "eggs", "tea"];
const yours = ["tea", "sugar", "milk"];
const yourSet = new Set(yours);
const common = mine.filter((item) => yourSet.has(item));
const all = new Set([...mine, ...yours]);
console.log(common, all.size);
[ 'milk', 'tea' ] 5

2.

const seen = new Set();
const questions = ["Q1", "Q2", "Q3"];
function nextQuestion() {
  const fresh = questions.filter((q) => !seen.has(q));
  if (fresh.length === 0) return null;
  seen.add(fresh[0]);
  return fresh[0];
}
console.log(nextQuestion(), nextQuestion(), nextQuestion(), nextQuestion());
Q1 Q2 Q3 null

3.

const stock = new Map([["chai", 20], ["samosa", 15]]);
const text = JSON.stringify(Object.fromEntries(stock));
const back = new Map(Object.entries(JSON.parse(text)));
console.log(text, back.get("samosa"), back instanceof Map);
const pairs = JSON.stringify([...stock]);
console.log(pairs, new Map(JSON.parse(pairs)).size);
{"chai":20,"samosa":15} 15 true
[["chai",20],["samosa",15]] 2

The pairs form also works when keys aren't strings.

  1. An object with no prototype has no inherited keys:
const obj = Object.create(null);
obj.constructor = 1;
console.log(obj.constructor);
1

(A Map is still the cleaner choice.)

Quick quiz

What does this print?

const s = new Set([3, 1, 3, 2, 1]);
s.add(1);
console.log(s.size, [...s].join(""));
  • A. 3 312
  • B. 3 123
  • C. 6 313211
  • D. 4 3121
Answer

A. A Set keeps each value once, in first-seen order: 3, 1, 2. Adding 1 again changes nothing. A Set doesn't sort.

Interview questions

  • What is a Set? How do you remove duplicates from an array in one line?
  • Why is set.has(x) faster than array.includes(x) for large data?
  • How does a Set decide two values are equal? What about two objects with the same contents?
  • What's the difference between a Map and a plain object?
  • Why can't you safely use a plain object as a dictionary of arbitrary words?
  • What happens when you use an object as a key in a plain object? In a Map?
  • How do you loop over a Map? In what order?
  • How do you convert a Map to JSON and back?
  • When would you use an array, a Set, an object or a Map?
  • What are WeakMap and WeakSet for?

Glossary

Term Meaning Example
Collection a value that holds many values array, object, Set, Map
Duplicate the same value appearing more than once "Asha" twice in visits
Set a collection where each value appears once new Set(["a", "b"])
Map a collection of key → value pairs with keys of any type new Map([["chai", 20]])
Key / value / entry the lookup name / the stored data / one key-value pair "chai" / 20 / ["chai", 20]
size number of values or entries in a Set or Map visitors.size
Lookup table (dictionary) a structure for finding a value by its key word → count
Hash table a structure that computes where a key lives and jumps there how Set and Map stay fast
Insertion order the order items were added Map and Set iterate in it
Reference equality two objects are equal only if they're the same object { id: 1 } !== { id: 1 }
Inherited property a property an object gets from its prototype constructor, toString
Object.prototype the prototype every plain object inherits from source of constructor
Object.entries(obj) an object as [key, value] pairs [["chai", 20]]
Object.fromEntries(pairs) pairs (or a Map) back into an object Object.fromEntries(map)
Object.create(null) an object with no prototype (no inherited keys) a safe plain dictionary
Iterable anything for...of can walk arrays, strings, Sets, Maps
Dedupe remove duplicates [...new Set(arr)]
WeakMap / WeakSet Map/Set with object keys that don't keep the objects alive per-object caches

Summary

  • Arrays are lists: includes scans every item, so "have I seen this?" gets slow.
  • Set keeps each value once; add, has, delete, size; [...new Set(arr)] dedupes. Objects compare by reference.
  • Plain objects as lookup tables break: inherited keys (constructor) and keys turned into strings ([object Object]).
  • Map has keys of any type, no inherited keys, set/get/has/delete/size, and insertion order. Never use map[key].
  • Convert with Object.entries / Object.fromEntries / spread; JSON of a Map or Set is {}, so convert first.
  • Unique → Set, lookup → Map, a record → object, an ordered list → array.

Next episode: Iterators and generators. How does for...of walk arrays, strings, Sets and Maps, and how do you make your own objects loop-able?