Sub topic 2
Map Fundamentals
This chapter assumes you know JavaScript variables, functions, objects and arrays, for...of loops, and the difference between primitive values and object references.
A Map is a built-in collection that stores key-value pairs. Any value can be a key, including objects, functions, and NaN. A plain object converts its keys to strings, but a Map keeps each key exactly as you passed it.
Creating a Map
You can create an empty Map, or pass in an iterable of [key, value] pairs to fill it.
const empty = new Map();
const prices = new Map([
['apple', 1.2],
['pear', 0.9]
]);
console.log(empty.size); // 0
console.log(prices.size); // 2size is a property, not a method. It always reflects the current number of entries.
The core operations
A Map has a small set of methods, and each one has a predictable return value.
| Method | What it does | Returns |
|---|---|---|
| `set(key, value)` | Adds or replaces an entry | The Map itself |
| `get(key)` | Reads the value for a key | The value, or `undefined` |
| `has(key)` | Checks whether a key exists | `true` or `false` |
| `delete(key)` | Removes an entry | `true` if it existed, else `false` |
| `clear()` | Removes all entries | `undefined` |
Because set returns the Map, you can chain calls:
const user = { id: 1 };
const visits = new Map();
visits.set(user, 3).set('total', 10);
console.log(visits.get(user)); // 3
console.log(visits.size); // 2
console.log(visits.has('total')); // true
visits.delete('total');
for (const [key, value] of visits) {
console.log(key, value); // { id: 1 } 3
}The object user works as a key here. The Map looks it up by reference, so only that same object finds the entry. A different object with identical contents does not. The chapter on SameValueZero covers the full comparison rules.
Updating an existing value
To update a value, call set again with the same key. The entry keeps its original position in the Map, and only its value changes.
const counts = new Map();
function record(word) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
record('hi');
record('hi');
record('bye');
console.log(counts.get('hi')); // 2
console.log(counts.get('bye')); // 1Common mistakes
get returns undefined both when a key is missing and when the stored value is undefined. If you need to tell those two cases apart, use has.
flowchart TD
A["map.get(key) returns undefined"] --> B{"map.has(key)?"}
B -- true --> C["Key exists, value is undefined"]
B -- false --> D["Key is missing"]Exercises
Exercise
After running const m = new Map(); m['a'] = 1; m.set('b', 2);, what are the values of m.size and m.get('a')?
Show answer
m.size is 1 and m.get('a') is undefined. Bracket assignment created a normal property on the object, not a Map entry, so only 'b' is stored in the Map.
Exercise
Given const k1 = { x: 1 }; const k2 = { x: 1 }; const m = new Map([[k1, 'first']]);, what does m.get(k2) return, and why?
Show answer
It returns undefined. Map compares object keys by reference. k2 is a different object from k1, even though its contents match.
Exercise
Write one expression that increments a counter stored under the key 'clicks' in a Map named stats and starts it at 1 if the key is missing.
Show answer
stats.set('clicks', (stats.get('clicks') ?? 0) + 1)