Objects & collections
Map
A dictionary with any keys, handy methods and a size.
Why it exists
A plain object is often used as a dictionary, but it wasn't designed for that: keys become strings (1 and "1" are the same), there are inherited keys like toString, and to get the size you need Object.keys(obj).length. Map was made for dictionaries: keys are anything and stay themselves, the methods say what they do, the size is in size, and the order is insertion order.
Where it's used
- Caches and memoization:
cache.has(arg) ? cache.get(arg) : …. - Counting arbitrary values: how many times each number appeared.
- Data attached to objects: a
Mapkeyed by DOM elements or users. - Interview tasks: two-sum, grouping, finding duplicates in one pass.
Syntax
const m = new Map();
m.set(key, value);
m.get(key);
m.has(key);
m.delete(key);
m.size;Examples
const stock = new Map();
stock.set("tea", 12);
stock.get("tea"); // → 12const m = new Map();
m.set(1, "number").set("1", "string");
m.size; // → 2
m.get(1); // → "number"1 and "1" are different keysconst counts = new Map();
for (const n of [3, 1, 3]) counts.set(n, (counts.get(n) ?? 0) + 1);
counts.get(3); // → 2const prices = new Map([["tea", 200], ["juice", 90]]);
[...prices.keys()]; // → ["tea", "juice"]Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
new Map() creates an empty collection, and new Map([[key, value], …]) a filled one.
set(key, value)adds or replaces a pair and returns theMapitself (calls can be chained);get(key)— the value, or undefined if the key is missing;has(key)— whether the key exists; more reliable than checkingget, since the value might be undefined or0;delete(key),clear()— remove one pair or all;size— how many pairs.
Keys are compared almost like ===: the number 1 and the string "1" are different keys, and an object is found only by a reference to the same object.
A Map is walked with for...of — as [key, value] pairs, in insertion order. There are also keys(), values() and entries().
Traps
How it differs from…
- Objects
{ } An object is for records with known fields (
{ name, price }); aMapis for dictionaries whose keys aren't known in advance, change often or aren't strings.
When to pick something else
For data with fixed fields (a user, a product) and anything you need to send as JSON, a plain object is simpler. A Map wins when keys are dynamic, aren't strings, or are many and often added and removed.
Practice
Lessons where this appears
- Why can't you fix a string?Why? · Chapter 6 · Strings
- Byte's cat showTale · Chapter 11 · Map and Set
- Why not a plain object?Why? · Chapter 11 · Map and Set
- The front deskWorkshop · Chapter 11 · Map and Set
- The case of the look-alike crowdInvestigation · Chapter 11 · Map and Set
- The DoppelgangerBoss · Chapter 11 · Map and Set