T5 Modern JavaScript (ES6 and later) · Lesson 10
Maps and sets
Two collections that plain objects and arrays cannot replace: Map, whose keys can be anything and keep their order, and Set, which holds each value once. Counting and grouping with them, moving between them and objects, arrays and JSON, union and intersection, and WeakMap for notes about objects you do not own.
- use a Map, with keys of any kind, and say when it beats a plain object
- walk a Map, and turn it to and from objects, arrays and JSON
- count and group a list with Map and groupBy, and remember results in a cache
- use a Set to keep values unique, and to test membership quickly
- find the union, the intersection and the difference of two sets
- use WeakMap and WeakSet for notes about objects, and say what makes them weak
The back cover
Objects and arrays carry most data, but two jobs suit them badly. One is looking things up by keys that are not text; the other is keeping a group where nothing may appear twice. Map and Set were made for those jobs.
These pages show Map, whose keys can be anything and keep their order, and how to walk it and turn it into other forms. They show counting, grouping and remembering answers with a Map. They show Set, which holds each value once, the questions two sets can answer, and WeakMap and WeakSet, which keep notes that vanish with their objects.
Before you start
The story: Forty clocks, one note
To keep a note on each clock, an apprentice made one object, and used each clock itself as a key. All forty notes went in without a murmur. When Master Hakim Verge opened the book, it held a single note, the last one written, under the strange heading [object Object].
The roster of bell-ringers has its own trouble: it counts Asha eleven times, once for each shift.
Master Verge turns the empty pages. "A plain object is a good shelf for things with names," he says. "It is a poor register for things that have no name but themselves. And a roster is not a list of shifts. It is a list of people."
Objects and arrays carry most of the data in JavaScript, and each has a job it does badly. An object's keys can only be text, so anything else is turned into text first. An array happily holds the same value many times, and finding one value means walking the list. Map and Set were added to do those two jobs properly.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Objects and keys. | stock.rice, stock["rice"] | A Map does this job for any key. |
| Object.entries and fromEntries. | [key, value] pairs | The bridge between objects and Maps. |
| includes. | list.includes("tea") | A Set answers the same question fast. |
| Spread. | [...list] | Turning a Set back into an array. |
| Destructuring in for...of. | for (const [k, v] of pairs) | Walking a Map. |
| Iterables. | Anything for...of can walk. | Maps and Sets are iterable. |
| Comparing objects. | {} === {} is false. | Object keys go by identity. |
| ??. | n ?? 0 | Counting from nothing. |
| JSON.stringify. | Text for storing or sending. | A Map needs converting first. |
| Closures. | A function that remembers. | A cache kept in a Map. |
By the end of this lesson you will be able to:
- use a Map, with keys of any kind, and say when it beats a plain object;
- walk a Map, and turn it to and from objects, arrays and JSON;
- count and group a list with Map and groupBy, and remember results in a cache;
- use a Set to keep values unique, and to test membership quickly;
- find the union, the intersection and the difference of two sets;
- use WeakMap and WeakSet for notes about objects, and say what makes them weak.
How to follow this lesson
When you choose a collection, ask what you will look things up by. By position: an array. By a fixed set of names you know while writing the code: an object. By a value that arrives while the program runs: a Map. Only whether something is there: a Set.
In one line
A Map is a table of any key to any value, and a Set is a collection that holds each value once; this lesson shows when each one beats an object or an array.
Map: a table of any key to any value
At a glance
A railway's lost-property office files each item under its tag, whatever the tag is: a ticket, a phone number, a coach and seat. A Map files values the same way, under keys of any kind.
A Map holds pairs of a key and a value. They are set and read with set, get, has and delete, and size counts them. Keys stay exactly as they are, so an object can be a key, and the number 1 and the string "1" stay apart.
Take a guess: Why can using a plain object as a lookup table be a security risk?
Here is what went wrong in the scene. A plain object's keys are text, so an object used as a key is first turned into text, and every plain object turns into the same text:
const north = { name: "North" };
const south = { name: "South" };
const notes = {};
notes[north] = "oiled";
notes[south] = "wound";
console.log(notes, Object.keys(notes).length);
{ '[object Object]': 'wound' } 1
Two clocks, one key, and the second note replaced the first, with no error. A Map keeps each key exactly as it was given:
A built-in collection of key and value pairs, made with new Map(). A key can be any value, an object included, and is kept as it is. Entries are read and written with methods, not with dots or square brackets.
const north = { name: "North" };
const south = { name: "South" };
const notes = new Map();
notes.set(north, "oiled");
notes.set(south, "wound");
console.log(notes.size, notes.get(north), notes.get(south));
2 oiled wound
The methods
A Map can start with an array of [key, value] pairs. set adds an entry, or replaces the value of a key it already has, and gives back the Map, so calls can be chained:
const stock = new Map([["rice", 12], ["dal", 7]]);
console.log(stock);
console.log(stock.get("rice"), stock.has("oil"), stock.get("oil"), stock.size);
stock.set("oil", 3).set("rice", 10);
stock.delete("dal");
console.log(stock);
Map(2) { 'rice' => 12, 'dal' => 7 }
12 false undefined 2
Map(2) { 'rice' => 10, 'oil' => 3 }
| Method | Does | Gives |
|---|---|---|
m.set(key, value) | adds or replaces an entry | the Map |
m.get(key) | reads a value | the value, or undefined |
m.has(key) | asks whether the key is there | true or false |
m.delete(key) | removes an entry | true if it was there |
m.size | counts the entries (a property) | a number |
m.clear() | removes everything | undefined |
Keys stay what they are
A Map treats the number 1 and the text "1" as two keys. A plain object turns both into the text 1, so the second replaces the first:
const m = new Map();
m.set(1, "number one");
m.set("1", "text one");
console.log(m.get(1), m.get("1"), m.size);
const o = {};
o[1] = "number one";
o["1"] = "text one";
console.log(o);
number one text one 2
{ '1': 'text one' }
| Plain object | Map | |
|---|---|---|
| keys | text and symbols | any value |
| number of entries | Object.keys(o).length | m.size |
| order of keys | mostly the order added, with number-like keys first | always the order added |
| a key that was never set | may find something built in, such as toString | only what you put there |
| good for | a record with names known while you write | a table filled in while the program runs |
Worked example 1
A bus depot keeps a note on each bus, and the buses are objects made elsewhere in the program. Keep a service date for each bus, without adding anything to the bus objects themselves, and look one up.
What we have: objects that are not yours to change, and a date for each
What we need: a date looked up by the bus itself
The plan: a Map with the bus objects as keys
const bus12 = { route: 12 };
const bus47 = { route: 47 };
const serviced = new Map();
serviced.set(bus12, "2 Nov");
serviced.set(bus47, "5 Nov");
console.log(serviced.get(bus47), serviced.has(bus12), Object.keys(bus47));
5 Nov true [ 'route' ]
Bus 47 was serviced on 5 Nov.
Check: bus47 still has only its route: the note lives in the Map.
A path that fails: a plain object with serviced[bus12] = .... Every bus becomes the key [object Object], so the depot has one date for all of them, and no error says so.
When you are stuck: a Map does not find what you put in
Read with get, not with a dot or square brackets.
Check the key's kind: 1 and "1" are different keys.
An object key must be the same object, not an equal one.
Print the Map: it shows every key and value.
Your turn
const m = new Map([["a", 1]]);
m.set("a", 2);
m.set("b", 3);
console.log(m.size, m.get("a"), m.delete("z"));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2 2 false
- Setting a again replaces its value, so there are two keys.
- a now holds 2.
- z was not there, so delete gives false.
It prints 2 2 false.
Why did the forty notes in the scene end up as one?Tap to reveal
- An object's keys are text.
- Every plain object turns into the same text.
Because every clock became the key [object Object].
How do you count the entries of a Map?Tap to reveal
- size is a property, not a method.
m.size
Did you know?
Objects as maps, and a known attack
Using a plain object as a lookup table can be dangerous. MDN warns that setting key-value pairs supplied by users on an object may let an attacker override the object's prototype, which can lead to prototype pollution attacks. The weakness has its own entry in MITRE's catalogue, CWE-1321, with Prototype Pollution as its other name. A Map has no prototype keys to reach.
Why it fits here: It answers this topic's question, and gives a security reason for Map: keys typed by people can never reach a prototype.
Sources: MDN: Map; MITRE: CWE-1321
Built for keys that come and go
A Map is built for keys that change often. MDN's comparison says a Map performs better where key-value pairs are added and removed often, while an object is not optimized for that. V8's team explains why: if many properties get added to and deleted from an object, keeping track of its shape costs a lot of time and memory, so V8 switches the object to slower properties.
Why it fits here: It gives a speed reason for this topic's Map: a table whose keys keep changing is the job Map was built for.
Sources: MDN: Map; V8 blog: Fast properties in V8
In one line
A Map holds pairs of any key and any value, set and read with set, get, has and delete, and counted with size. Keys stay as they are, so objects can be keys, and 1 and "1" stay apart.
Walking a Map, and moving between forms
At a glance
A visitors' book is read in the order people signed it. A Map is walked the same way, in the order its keys were added.
Walking a Map gives [key, value] pairs. Spread turns it into an array of pairs, and Object.fromEntries turns it into a plain object. But JSON.stringify of a Map gives {}, an empty object, so convert it first, or its data is lost on the way. Both forms can be turned back into a Map again with new Map(...).
Take a guess: Why does JSON.stringify turn a Map into an empty object?
A Map is iterable, and each step gives a [key, value] pair. So the pattern from the destructuring lesson fits exactly. Three methods give the keys, the values or the pairs alone, each as an iterator, which spread turns into an array:
const stock = new Map([["rice", 12], ["dal", 7]]);
for (const [item, n] of stock) console.log(item, n);
console.log([...stock.keys()], [...stock.values()], [...stock.entries()]);
rice 12
dal 7
[ 'rice', 'dal' ] [ 12, 7 ] [ [ 'rice', 12 ], [ 'dal', 7 ] ]
A Map always walks its entries in the order they were first added. Changing a value leaves its key where it was:
const m = new Map([["b", 1], ["a", 2]]);
m.set("c", 3);
m.set("b", 9);
console.log([...m.keys()]);
[ 'b', 'a', 'c' ]
A Map also has forEach. Its function receives the value first and the key second, the same order as an array's forEach, which gives the item first and the index second:
new Map([["rice", 12]]).forEach((n, item) => console.log(item, n));
rice 12
To and from objects and arrays
Object.entries gives the pairs that a Map starts from, and Object.fromEntries reads the pairs that a Map gives. So the two forms turn into each other in one step:
const prices = { tea: 15, dosa: 80 };
const m = new Map(Object.entries(prices));
console.log(m.get("tea"), Object.fromEntries(m));
const copy = new Map(m);
copy.set("tea", 20);
console.log(m.get("tea"), copy.get("tea"));
15 { tea: 15, dosa: 80 }
15 20
new Map(old) makes a separate copy of the table, one level deep, as object spread does.
A Map in JSON
JSON has no form for a Map. JSON.stringify sees an object with no properties of its own, and writes an empty pair of braces, with no error. The data is gone unless you convert it first:
const m = new Map([["a", 1]]);
console.log(JSON.stringify(m), JSON.stringify([...m]), JSON.stringify(Object.fromEntries(m)));
{} [["a",1]] {"a":1}
Use the array of pairs when the keys are not all text, and fromEntries when they are, as the object form is easier for other programs to read.
| From | To | Write |
|---|---|---|
| an object | a Map | new Map(Object.entries(obj)) |
| a Map | an object | Object.fromEntries(m) |
| a Map | an array of pairs | [...m] |
| an array of pairs | a Map | new Map(pairs) |
| a Map | JSON | JSON.stringify([...m]) |
Worked example 2
A shop stores its prices as JSON, as an object, because that is what its server sends. While the program runs, it keeps them in a Map. Read the JSON into a Map, raise tea by ₹5, and write it back as JSON.
What we have: JSON text of an object
What we need: new JSON text with the changed price
The plan: JSON.parse, then new Map(Object.entries(...)); after the change, Object.fromEntries and JSON.stringify
const saved = '{"tea":15,"dosa":80}';
const prices = new Map(Object.entries(JSON.parse(saved)));
prices.set("tea", prices.get("tea") + 5);
console.log(JSON.stringify(Object.fromEntries(prices)));
{"tea":20,"dosa":80}
The new JSON is {"tea":20,"dosa":80}.
Check: dosa is unchanged, and tea is 15 + 5.
A path that fails: JSON.stringify(prices). It gives {}, with no error, and the whole price list is lost on the next save.
When you are stuck: a Map does not convert or walk as you expect
{} from JSON.stringify means a Map went in: convert it first.
forEach gives the value first, then the key.
keys, values and entries give iterators: spread them into an array to print or sort.
To sort a Map, spread it, sort the pairs, and make a new Map from them.
Your turn
const m = new Map([["x", 1], ["y", 2]]);
const doubled = new Map([...m].map(([k, v]) => [k, v * 2]));
console.log(doubled.get("y"), m.get("y"));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4 2
- Spread gives the pairs, and map makes new pairs.
- The original Map is unchanged.
It prints 4 2.
In what order does a Map give its keys?Tap to reveal
- It remembers when each key was first added.
The order they were first added.
Write the line that gives a plain object from the Map m.Tap to reveal
- fromEntries reads pairs, and a Map gives pairs.
Object.fromEntries(m)
Did you know?
JSON has no word for a Map
JSON has no way to write a Map. Its standard, RFC 8259, says JSON can represent four primitive types, strings, numbers, booleans and null, and two structured types, objects and arrays. A Map is neither, so JSON.stringify writes it as an empty object, unless it is first turned into an array of pairs or a plain object.
Why it fits here: It answers this topic's question: JSON knows only objects and arrays, so a Map must be converted before it is written.
Source: RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format
The way back to an object
Turning a Map into a plain object has a method of its own. MDN describes Object.fromEntries as transforming a list of key-value pairs into an object, and a Map walks as exactly such pairs. The 2019 edition of the standard defines it, and TC39's list of finished proposals names its author, Darien Maillet Valentine.
Why it fits here: It names this topic's way back from a Map to a plain object, ready for JSON.stringify.
Sources: MDN: Object.fromEntries(); ECMAScript 2019 Language Specification; TC39: Finished Proposals
In one line
A Map walks as [key, value] pairs, in the order keys were added. It turns into an array with spread and into an object with Object.fromEntries. JSON.stringify of a Map gives {}, so convert it first.
Counting, grouping and remembering
At a glance
A teacher counting votes for class monitor makes a tally beside each name. A Map keeps such a tally in code, one count under each key.
The line m.set(k, (m.get(k) ?? 0) + 1) adds one to a count, starting from 0 for a new key. Grouping sorts a list into groups by a function's answer. And a cache keeps answers under their questions; test it with has, so that a stored answer of 0 still counts as found. Asking the cache first saves working the answer out again.
Take a guess: Who gave the name memo functions to answers kept for later, and when?
Three jobs come up in nearly every program, and a Map suits all of them, as their keys arrive while the program runs.
Counting
To count how often each word appears, read the count so far, add one, and write it back. A word not seen before gives undefined, and ?? 0 starts it from zero:
const words = ["tea", "dal", "tea", "oil", "tea"];
const counts = new Map();
for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
console.log(counts);
Map(3) { 'tea' => 3, 'dal' => 1, 'oil' => 1 }
To find the most common, spread the Map into pairs, and sort them by their second item:
const counts = new Map([["tea", 3], ["dal", 1], ["oil", 2]]);
const top = [...counts].toSorted((a, b) => b[1] - a[1]);
console.log(top[0], top.map(([w]) => w));
[ 'tea', 3 ] [ 'tea', 'oil', 'dal' ]
Grouping
Sorting a list into groups by some property used to take a loop. Object.groupBy does it in one call: it gives each item to your function, and collects the items by the answer. Map.groupBy does the same into a Map, whose keys may be anything:
const orders = [
{ item: "tea", kind: "drink" },
{ item: "dosa", kind: "food" },
{ item: "coffee", kind: "drink" },
];
const byKind = Object.groupBy(orders, (o) => o.kind);
console.log(Object.keys(byKind), byKind.drink.length);
const m = Map.groupBy(orders, (o) => o.kind);
console.log(m.get("food").map((o) => o.item));
[ 'drink', 'food' ] 2
[ 'dosa' ]
Remembering: a cache
A slow job asked the same question twice should not do the work twice. A cache keeps each answer under its question, and a Map is the natural place for it. The has check matters: an answer of 0 or an empty text would look missing to a plain truthiness test.
const cache = new Map();
function square(n) {
if (cache.has(n)) return `${cache.get(n)} (saved)`;
const result = n * n;
cache.set(n, result);
return result;
}
console.log(square(9), square(9), cache.size);
81 81 (saved) 1
| Job | Key | Value | Line |
|---|---|---|---|
| counting | the thing counted | its count | m.set(k, (m.get(k) ?? 0) + 1) |
| grouping | the group's name | an array of items | Map.groupBy(list, fn) |
| remembering | the question | the answer | if (m.has(k)) return m.get(k); |
Worked example 3
The tower's log lists each stroke with its ringer. Work out how many strokes each ringer struck, and name the busiest.
What we have: a list of ringers' names, one for each stroke
What we need: a count for each ringer, and the busiest
The plan: count into a Map, spread it into pairs, sort by the count, and take the first
const log = ["Asha", "Ravi", "Asha", "Meera", "Asha", "Ravi"];
const strokes = new Map();
for (const name of log) strokes.set(name, (strokes.get(name) ?? 0) + 1);
const [busiest] = [...strokes].toSorted((a, b) => b[1] - a[1]);
console.log(strokes.get("Ravi"), busiest);
2 [ 'Asha', 3 ]
Ravi struck 2, and Asha was the busiest, with 3.
Check: the counts 3, 2 and 1 add up to the 6 strokes in the log.
A path that fails: strokes.set(name, strokes.get(name) + 1), with no ?? 0. The first time a name appears, undefined + 1 gives NaN, and every count stays NaN from then on.
When you are stuck: a count or a group goes wrong
NaN in a count means the first read gave undefined: write ?? 0.
For sorting, spread the Map into pairs first.
groupBy needs a function that gives the group's name for each item.
In a cache, test with has, as a saved answer may be 0 or empty.
Your turn
const seen = new Map();
for (const c of "abca") seen.set(c, (seen.get(c) ?? 0) + 1);
console.log(seen.get("a"), seen.size);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2 3
- for...of walks a string by its characters.
- a appears twice, and there are three different letters.
It prints 2 3.
Why does a cache test with cache.has(n) and not cache.get(n)?Tap to reveal
- A saved answer may be 0.
- 0 is falsy, so a plain test would treat it as missing.
Because has works even for answers that are falsy.
What is the key of a grouping by kind?Tap to reveal
- The function gives each item's group.
The kind; the value is an array of the items of that kind.
Did you know?
Memo functions, 1968
Remembering answers under their questions has a name, memoization. On 6 April 1968 Donald Michie published "Memo" Functions and Machine Learning in the journal Nature, and Wikipedia traces the word to the Latin memorandum, to be remembered. A cache built with a Map does the same job: it looks up the question before working the answer out again.
Why it fits here: It answers this topic's question, and names its cache: keeping answers under their questions is called memoization.
Sources: Nature: "Memo" Functions and Machine Learning; Wikipedia: Memoization
React remembers too
React builds this topic's cache into its components. Its useMemo hook lets a component cache the result of a calculation between re-renders, working it out again only when its inputs change. React's documentation adds that the React Compiler memoizes values and functions automatically, reducing the need for useMemo written by hand.
Why it fits here: It shows this topic's cache in a popular library: React keeps answers between renders, as a Map keeps them between calls.
Source: React: useMemo
In one line
A Map counts with m.set(k, (m.get(k) ?? 0) + 1), and groupBy sorts a list into groups by a function's answer. A cache keeps answers under their questions: test with has, so that an answer of 0 still counts.
Set: each value once
At a glance
A guest list for a wedding needs each name once, however many times it was suggested. A Set keeps a list like that by itself.
A Set holds each value once, in the order first added, with add, has, delete and size. Adding a value that is there already changes nothing. The line [...new Set(list)] removes repeats in one go, and has is far faster than includes on a long list. Objects go by identity: two objects that look alike are still two members.
Take a guess: Does a Set keep NaN once or twice, when NaN is not equal to itself?
The tower's roster counted Asha eleven times, once for each shift. A roster wants each person once, and an array cannot promise that. A Set can.
A built-in collection that holds each value once, made with new Set() or from any iterable. Adding a value it already holds changes nothing. Values stay in the order they were first added.
const ringers = new Set(["Asha", "Ravi", "Asha"]);
console.log(ringers, ringers.size, ringers.has("Ravi"), ringers.has("Meera"));
ringers.add("Meera").add("Asha");
ringers.delete("Ravi");
console.log(ringers);
Set(2) { 'Asha', 'Ravi' } 2 true false
Set(2) { 'Asha', 'Meera' }
Three names went in, and two stayed, because Asha came twice. Adding Asha again later changed nothing.
Removing repeats from a list
This is the most common use of a Set, and it takes one line. Make a Set from the list, and spread it back into an array. The first appearance of each value keeps its place:
const names = ["Asha", "Ravi", "Asha", "Meera", "Ravi"];
console.log([...new Set(names)], new Set(names).size);
console.log([...new Set("banana")].join(""));
[ 'Asha', 'Ravi', 'Meera' ] 3
ban
A string is iterable too, so a Set of a string holds its different letters. A Set is iterable like a Map, so for...of walks it, one value at a time. It has no index: there is no s[0], because a Set is about whether a value is there, not where.
Objects go by identity
Two objects with the same contents are still two objects, as {} === {} is false, so a Set keeps both:
const s = new Set([{ id: 1 }, { id: 1 }]);
console.log(s.size);
2
To keep one object for each id, use a Map from id to object: new Map(list.map((o) => [o.id, o])).
Asking whether a value is there
includes walks an array from the start until it finds the value, so a long list takes long. A Set goes straight to the value. Here are two thousand lookups in 2,00,000 numbers, measured with the clock:
const big = Array.from({ length: 200000 }, (_, i) => i);
const set = new Set(big);
let t = performance.now();
for (let i = 0; i < 2000; i++) big.includes(199999 - i);
const listTime = performance.now() - t;
t = performance.now();
for (let i = 0; i < 2000; i++) set.has(199999 - i);
const setTime = performance.now() - t;
console.log(setTime * 5 < listTime);
true
The block prints true because the Set took less than a fifth of the array's time, and in practice far less. For a list of ten items the difference does not matter; for a list of thousands checked again and again, it does.
| Array | Set | |
|---|---|---|
| repeats | allowed | each value once |
| order | by position, with indexes | the order added, with no indexes |
| is it there? | list.includes(x) walks the list | s.has(x) goes straight to it |
| good for | an ordered list, repeats and all | membership and unique values |
Worked example 4
A school's gate logs each student's card number at every entry. How many different students came in today, and has card 305 been seen? The log is long, and it is checked many times.
What we have: a long list with repeats
What we need: the number of different cards, and a quick check for one
The plan: make a Set from the log, read its size, and use has
const gate = [101, 305, 101, 207, 305, 305, 412];
const came = new Set(gate);
console.log(came.size, came.has(305), came.has(999));
4 true false
4 different students came in, and card 305 was seen.
Check: the different cards are 101, 305, 207 and 412.
A path that fails: gate.length, which counts entries and not students: 7, as card 305 came in three times.
When you are stuck: a Set does not behave like an array
No length: use size.
No index: spread it into an array, or walk it with for...of.
Two equal objects stay apart: objects go by identity.
To turn it back into an array, write [...s].
Your turn
const s = new Set([1, 2]);
console.log(s.add(2).size, s.add(3).size, s.delete(9));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2 3 false
- 2 is already there, so the size stays 2.
- 3 is new: size 3.
- 9 was not there, so delete gives false.
It prints 2 3 false.
Remove the repeats from the array tags, in one line.Tap to reveal
- A Set drops the repeats, and spread makes an array again.
const unique = [...new Set(tags)];
Why does s[0] give undefined for a Set?Tap to reveal
- A Set has no positions.
Because a Set has no indexes.
Did you know?
Sets began with Cantor
The idea of a set is younger than it sounds. Wikipedia says set theory, as modern mathematicians understand it, was founded by an 1874 paper of Georg Cantor. The Stanford Encyclopedia of Philosophy dates its birth to late 1873, when Cantor discovered that the points of the real line cannot be counted. JavaScript's Set borrows the name and the main rule: each member once.
Why it fits here: It gives this topic's Set its name and its rule: a collection in which each member appears once, as in mathematics.
Sources: Wikipedia: Set theory; Stanford Encyclopedia of Philosophy: Set Theory
NaN, once
A Set keeps NaN only once, though NaN is not equal to itself. MDN explains that Map and Set compare with the SameValueZero algorithm, which treats NaN as the same as NaN and otherwise follows ===. It once used SameValue, which kept 0 and −0 apart; the standard's steps now turn a key of −0 into 0 before storing it.
Why it fits here: It answers this topic's question: a Set holds one NaN, and treats 0 and −0 as the same member.
Sources: MDN: Map; ECMAScript Language Specification: CanonicalizeKeyedCollectionKey
In one line
A Set holds each value once, in the order first added: add, has, delete and size. [...new Set(list)] removes repeats in one line, and has is far faster than includes on a long list. Objects go by identity.
Comparing two sets
At a glance
Two clubs share some members: who belongs to either, who to both, who to one but not the other? Sets answer such questions directly.
The method union gives the members of either set, intersection those of both, and difference those in this set and not that one, so difference has a direction. Each gives a new Set and leaves the old ones alone. The methods isSubsetOf and isDisjointFrom answer with true or false. Before these methods, each question took a filter and has.
Take a guess: When did JavaScript's Set gain union and intersection?
Questions about two groups come up all the time. Who rang both weeks? Who rang last week and not this week? Everybody who rang at all? These are the set operations of mathematics, and Set has a method for each. Each one gives a new Set, and leaves the two it was given unchanged.
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log(a.union(b), a.intersection(b), a.difference(b));
console.log(a.symmetricDifference(b));
Set(4) { 1, 2, 3, 4 } Set(2) { 2, 3 } Set(1) { 1 }
Set(2) { 1, 4 }
| Method | Gives | For a = {1, 2, 3}, b = {2, 3, 4} |
|---|---|---|
a.union(b) | everything in either | 1, 2, 3, 4 |
a.intersection(b) | what is in both | 2, 3 |
a.difference(b) | what is in a and not in b | 1 |
a.symmetricDifference(b) | what is in exactly one | 1, 4 |
Mind the order in difference: a.difference(b) and b.difference(a) are different answers. The first is what a has that b lacks.
Questions with a yes or no
Three more methods answer true or false. isSubsetOf asks whether everything here is also there; isSupersetOf asks the reverse; isDisjointFrom asks whether the two have nothing in common:
const a = new Set([1, 2, 3]);
console.log(new Set([2]).isSubsetOf(a), a.isSupersetOf(new Set([2])), a.isDisjointFrom(new Set([9])));
true true true
These methods joined the language in ES2025, so older browsers lack them. MDN's compatibility table, as lesson 01 showed, says which. For code that must run in older browsers, a filter does the same job: [...a].filter((x) => b.has(x)) is the intersection, as an array.
Worked example 5
Here are the ringers of two weeks. Find who rang both weeks, who has dropped out since last week, and how many people rang at all.
What we have: two lists of names, with repeats
What we need: three answers about the two weeks
The plan: make a Set from each list; intersection gives both weeks, difference gives the dropped, and union gives everybody
const lastWeek = new Set(["Asha", "Ravi", "Meera", "Asha"]);
const thisWeek = new Set(["Ravi", "Kabir", "Asha"]);
console.log([...lastWeek.intersection(thisWeek)]);
console.log([...lastWeek.difference(thisWeek)]);
console.log(lastWeek.union(thisWeek).size);
[ 'Asha', 'Ravi' ]
[ 'Meera' ]
4
Asha and Ravi rang both weeks, Meera dropped out, and 4 people rang at all.
Check: Asha, Ravi, Meera and Kabir are the four names.
A path that fails: adding the two sizes for the number of people: 3 + 3 = 6. Asha and Ravi are counted twice; the union counts each person once.
When you are stuck: a set operation gives the wrong group
Say it in words first: in both, in either, in this and not in that.
Difference has a direction: a.difference(b) is not b.difference(a).
The result is a Set: spread it to get an array.
If the method is not a function, the browser is too old: use filter with has.
Your turn
const x = new Set(["a", "b"]);
const y = new Set(["b", "c"]);
console.log([...y.difference(x)], x.union(y).size, x.isDisjointFrom(y));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 'c' ] 3 false
- y has c, which x lacks.
- Together: a, b, c.
- They share b, so they are not disjoint.
It prints [ 'c' ] 3 false.
Which method finds what two sets have in common?Tap to reveal
- It is the middle of two overlapping circles.
a.intersection(b)
How do you find the customers of last month who did not come this month?Tap to reveal
- Those in last month's set and not in this month's.
lastMonth.difference(thisMonth)
Did you know?
Union and friends, since 2024
Comparing two sets once took loops. Set now has methods named after set theory: union, intersection, difference, symmetricDifference, isSubsetOf and more. MDN shows union working in the latest browsers since June 2024, and TC39's list of finished proposals names New Set methods, by Michał Wadas, Sathya Gunasekaran and Kevin Gibbons.
Why it fits here: It answers this topic's question: union, intersection and difference joined JavaScript in 2024.
Sources: MDN: Set.prototype.union(); TC39: Finished Proposals
Circles from Euler to Venn
The pictures used for this topic are older than computers. Wikipedia says the Venn diagram, which shows the logical relation between sets, was popularized by John Venn in the 1880s. The Stanford Encyclopedia of Philosophy traces the line further back: Euler drew circles for terms in the 18th century, and a century later Venn expanded what they could express.
Why it fits here: It gives this topic's union and intersection their classic picture: overlapping circles, drawn since Euler and Venn.
Sources: Wikipedia: Venn diagram; Stanford Encyclopedia of Philosophy: Diagrams
In one line
Sets answer questions about two groups: union for either, intersection for both, difference for this and not that, which has a direction. Each gives a new Set; isSubsetOf and isDisjointFrom give true or false.
Notes that do not hold on: WeakMap and WeakSet
At a glance
A sticky note on a library book goes back to the shelf with the book, and is thrown away when the book is withdrawn. WeakMap keeps notes like that about objects.
WeakMap and WeakSet take objects only, and do not keep them alive: when nothing else holds an object, its note vanishes with it. They have no size and cannot be walked, since what they hold may change at any moment. Use them for notes about objects you do not own, such as DOM elements.
Take a guess: Who invented the garbage collection that makes weak notes vanish?
A Map holds on to its keys. If a key is an object that the rest of the program has finished with, such as an element removed from the page, the Map keeps it in memory for as long as the Map lives. In a long-running page, notes about old objects pile up. A WeakMap does not hold on.
A Map whose keys must be objects, and which does not keep them alive. MDN explains that when nothing else in the program can reach a key, the entry may be removed, and the memory reused. It has get, set, has and delete, and no size and no way to walk it.
const notes = new WeakMap();
const clock = { name: "West" };
notes.set(clock, "needs oil");
console.log(notes.get(clock), notes.has({ name: "West" }), notes.size);
needs oil false undefined
It has no size, and it cannot be walked, for a good reason: entries may disappear at any moment, whenever the engine reclaims memory, so a count would mean nothing. Only someone who holds the key can ask about it. Keys must be objects, or the rarely used symbols, since a text such as "West" can be made again at any time, and is never really gone:
const notes = new WeakMap();
notes.set("West", 1);
Uncaught TypeError: Invalid value used as weak map key
at line 2
Its usual job is keeping notes about objects that belong to someone else, such as elements on a page, without adding anything to them. This page keeps a click count for each button in a WeakMap:
<!DOCTYPE html>
<button id="a">0</button>
<button id="b">0</button>
<script>
const clicks = new WeakMap();
for (const button of document.querySelectorAll("button")) {
clicks.set(button, 0);
button.addEventListener("click", () => {
clicks.set(button, clicks.get(button) + 1);
button.textContent = clicks.get(button);
});
}
</script>
Checked in Chrome
- two clicks on the first button show 2
- the second button keeps its own count, 1
When a button is removed from the page and nothing else refers to it, its entry goes too, with no code to clear it up.
WeakSet
A WeakSet is the same idea for a Set: it holds objects only, without keeping them alive, and can only answer has. It suits marks such as already seen:
const seen = new WeakSet();
const first = { id: 1 };
seen.add(first);
console.log(seen.has(first), seen.has({ id: 1 }));
true false
| Map or Set | WeakMap or WeakSet | |
|---|---|---|
| keys | any value | objects only |
| keeps its keys alive | yes | no |
| size, and walking | yes | no |
| good for | data of your own | notes about objects you do not own |
Worked example 6
A page draws many cards, and each one needs to remember how many times it has been opened. Cards are removed as the customer scrolls. Keep the counts without changing the card objects, and without a table that grows for ever.
What we have: objects that come and go, and a number for each
What we need: a count for each card that goes when the card goes
The plan: a WeakMap from card to count; the count is read with ?? 0, as a card may have none yet
const opened = new WeakMap();
function open(card) {
const n = (opened.get(card) ?? 0) + 1;
opened.set(card, n);
return n;
}
const card = { title: "Thali" };
open(card);
console.log(open(card), Object.keys(card));
2 [ 'title' ]
The card has been opened 2 times, and the card object is unchanged.
Check: Object.keys shows only title: the count lives outside the card.
A path that fails: a plain Map. It works, and it keeps every removed card in memory for as long as the page stays open.
When you are stuck: a WeakMap refuses something
Invalid value used as weak map key means the key was not an object.
size is undefined, and for...of fails: weak collections cannot be counted or walked.
If you need to list the entries, use a Map.
An equal object is not the same key: hold on to the object itself.
Your turn
Why does a WeakMap have no size?Tap to reveal
- Its entries may go at any moment, when memory is reclaimed.
Because the count could change without any code running.
Can a text be a WeakMap's key?Tap to reveal
- Keys must be objects.
No: it is a TypeError.
When is a Map better than a WeakMap?Tap to reveal
- When you need to count or walk the entries, or use keys that are not objects.
When you need size, walking, or keys that are not objects.
Did you know?
Best avoided
JavaScript has a weaker tool still, and its own documentation warns against it. WeakRef, a reference that does not keep its object alive, came with the WeakRefs proposal, whose champions include Dean Tribble and Mark Miller. MDN says correct use of WeakRef takes careful thought and is best avoided if possible, because when, how and whether garbage collection happens is down to each engine.
Why it fits here: It marks the limit of this topic's weak collections: they are safe to use, while WeakRef asks you to predict the garbage collector.
Sources: MDN: WeakRef; TC39: Finished Proposals
Garbage collection, 1959
The memory clean-up behind this topic is older than JavaScript by decades. Wikipedia credits John McCarthy with inventing garbage collection around 1959, to simplify manual memory management in Lisp: the system, not the programmer, decides which memory to free. MDN adds that all modern JavaScript engines ship a mark-and-sweep collector, which treats an object that cannot be reached as no longer needed.
Why it fits here: It answers this topic's question, and explains what weak notes rely on: memory nobody can reach is freed by itself.
Sources: Wikipedia: Garbage collection (computer science); MDN: Memory management
In one line
WeakMap and WeakSet take objects only and do not keep them alive, so notes about objects vanish with the objects. They have no size and cannot be walked. Use them for notes about objects you do not own.
Where it is used
Maps and Sets are in most programs of any size. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| Map with any keys | tables filled in while a program runs | a note for each bus, kept outside the bus |
| counting | reports | strokes by ringer, words in a text |
| grouping | lists shown under headings | orders by kind |
| a cache | slow work asked for twice | answers from a server kept for later |
| Set for unique values | rosters and tags | different students through a gate |
| union and difference | comparing two groups | customers of last month who did not return |
| WeakMap | notes on objects you do not own | a click count for each element |
Mistakes and debugging
These are the slips that people meet most often with Maps and Sets. Every output below is the real one, from the code shown.
1. An object as a plain object's key
const a = { name: "North" };
const b = { name: "South" };
const notes = {};
notes[a] = "oiled";
console.log(notes[b]);
oiled
No error: both objects became the key [object Object], so b found a's note. The fix: a Map.
2. A dot on a Map
const m = new Map([["rice", 12]]);
console.log(m["rice"], m.rice, m.get("rice"));
undefined undefined 12
No error: entries are not properties. The fix: get.
3. A property set on a Map
const m = new Map();
m.tea = 15;
console.log(m.size, m.get("tea"), m.tea);
0 undefined 15
No error: this added a property to the Map object, and no entry. The fix: m.set("tea", 15).
4. A Map turned straight into JSON
console.log(JSON.stringify(new Map([["a", 1]])));
{}
No error, and no data. The fix: JSON.stringify(Object.fromEntries(m)).
5. An equal object as a key
const m = new Map();
m.set({ id: 1 }, "x");
console.log(m.get({ id: 1 }));
undefined
No error: the second { id: 1 } is another object. The fix: keep the key in a const, or use the id, which is a number, as the key.
6. A plain object given to new Map
const m = new Map({ a: 1 });
Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
at line 1
A Map starts from pairs. The fix: new Map(Object.entries({ a: 1 })).
7. Treating a Set as an array
const s = new Set([3, 1, 2]);
console.log(s[0], s.length, s.size);
undefined undefined 3
No error: a Set has no indexes and no length. The fix: size, or spread it into an array.
The debugging corner: print the collection
A Map or a Set prints its whole contents with console.log: Map(2) { 'rice' => 12, 'dal' => 7 }. The number in brackets is its size. If a key seems missing, check its kind in the printout: 1 and '1' print differently. An empty Map(0) with properties beside it means dots were used in place of set.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
// a Map: any keys, kept as they are, in the order added
const stock = new Map([["rice", 12]]);
stock.set("dal", 7);
console.log(stock.get("rice"), stock.has("oil"), stock.size);
for (const [item, n] of stock) console.log(item, n);
// counting, with ?? 0 for the first time
const counts = new Map();
for (const w of ["tea", "dal", "tea"]) counts.set(w, (counts.get(w) ?? 0) + 1);
console.log(counts.get("tea"));
// to and from objects and JSON
console.log(JSON.stringify(Object.fromEntries(stock)));
console.log(new Map(Object.entries({ tea: 15 })).get("tea"));
// a Set: each value once
const names = ["Asha", "Ravi", "Asha"];
console.log([...new Set(names)]);
// comparing two groups
const last = new Set(["Asha", "Ravi"]);
const now = new Set(["Ravi", "Kabir"]);
console.log([...last.intersection(now)], [...last.difference(now)], last.union(now).size);
// notes on objects you do not own
const notes = new WeakMap();
const clock = {};
notes.set(clock, "oiled");
console.log(notes.get(clock));
12 false 2
rice 12
dal 7
2
{"rice":12,"dal":7}
15
[ 'Asha', 'Ravi' ]
[ 'Ravi' ] [ 'Asha' ] 3
oiled
| When you see | It means | Look at |
|---|---|---|
[object Object] as a key | an object used as a plain object's key | a Map |
| undefined from a Map you just filled | a dot in place of get, or an equal object as the key | get, and the same object |
{} from JSON.stringify | a Map or a Set went in | fromEntries, or spread |
| NaN in a count | undefined + 1 on the first time | ?? 0 |
TypeError: object is not iterable | a plain object given to new Map | Object.entries |
TypeError: Invalid value used as weak map key | a key that is not an object | an object key, or a Map |
The story: A register that knows its keys
You keep the notes in a Map, whose keys may be the clocks themselves, so each clock has its own entry. You keep the ringers in a Set, which holds each name once, however many shifts it worked. With the two rosters as Sets, working out who rang last week and not this week takes one line.
The book now holds forty notes, and the roster nine names.
Master Verge closes the book on the last bench of the upper floor. "That is every clock up here," he says, and hands you a heavy iron key. "The machines that run them are below the streets, in the Underway. Mind your head on the stairs."
Reagents gathered: Map, Set, WeakMap, union, groupBy, Object.fromEntries.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)