Sub topic 2
Map Fundamentals
This chapter assumes you know JavaScript variables, functions, arrow functions, objects, arrays, and the difference between primitive values and object references. It covers how to create a Map, read and write entries, and the mistakes developers make most often with the basic API. Iteration, key equality rules, and the Map-versus-object comparison each get their own chapter later.
The working model
A Map is an ordered collection of key-value pairs, called entries. It has three properties that set it apart from a plain object:
- Keys can be any value: strings, numbers, booleans,
null,undefined, functions, objects, or symbols. - The Map remembers the order in which keys were first inserted.
- You read and write entries only through methods (
set,get,has,delete,clear) and you read the entry count from thesizeproperty.
The basic example below shows all of these:
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 is the key itself. It is not converted to the string "[object Object]", which is what happens when you use an object as a property name on a plain object.
Creating a Map
The Map constructor takes an optional iterable whose items are [key, value] pairs. Arrays of two-element arrays are the most common input.
const empty = new Map();
const prices = new Map([
['apple', 1.2],
['pear', 0.9]
]);
const copy = new Map(prices); // a Map is itself an iterable of pairs
console.log(empty.size); // 0
console.log(prices.get('pear')); // 0.9
console.log(copy === prices); // false
console.log(copy.get('apple')); // 1.2Copying with new Map(prices) is shallow. The new Map has its own entries, but if a value is an object, both Maps point to the same object.
Constructor edge cases
| Argument | Result |
|---|---|
| Nothing, `undefined`, or `null` | An empty Map |
| An array of `[key, value]` arrays | One entry per pair |
| An existing Map | A shallow copy |
| An array of primitives, such as `[1, 2]` | `TypeError`, because each item must be an object |
| A non-iterable, such as `42` or `{}` | `TypeError` |
| A pair with extra items, such as `['a', 1, 2]` | Extra items are ignored |
| A pair with a missing value, such as `['a']` | The value is `undefined` |
| Duplicate keys | The last value wins, at the first key's position |
try {
new Map([1, 2]);
} catch (err) {
console.log(err instanceof TypeError); // true
}
const dupes = new Map([['a', 1], ['b', 2], ['a', 3]]);
console.log(dupes.get('a')); // 3
console.log(dupes.size); // 2The core methods
| Member | Returns | Notes |
|---|---|---|
| `set(key, value)` | The Map | Adds or overwrites an entry, so you can chain calls |
| `get(key)` | The value, or `undefined` | Returns `undefined` for missing keys |
| `has(key)` | Boolean | The only reliable way to check whether a key exists |
| `delete(key)` | Boolean | `true` if an entry was removed |
| `clear()` | `undefined` | Removes every entry |
| `size` | Number | A read-only getter, not a method |
const m = new Map([['a', 1], ['b', 2]]);
console.log(m.delete('a')); // true
console.log(m.delete('a')); // false, already gone
m.clear();
console.log(m.size); // 0size is an accessor property, so calling m.size() throws a TypeError. Assigning to it, as in m.size = 10, has no effect in sloppy mode and throws in strict mode. That includes modules and class bodies.
Overwriting keeps the original position
When you call set with a key that already exists, the Map replaces the value but keeps the entry where it was. The order changes only if you delete the key and add it again.
const order = new Map([['a', 1], ['b', 2]]);
order.set('a', 99);
console.log([...order.keys()]); // ['a', 'b']
order.delete('a');
order.set('a', 100);
console.log([...order.keys()]); // ['b', 'a']You can use this to move a key to the end, as in a simple least-recently-used cache.
get versus has
get returns undefined in two different situations: the key is missing, or the key is present and its value is undefined. If your Map can hold undefined, null, 0, '', or false as values, check for the key with has and do not rely on a truthiness test.
const flags = new Map([['beta', false], ['legacy', undefined]]);
console.log(flags.get('legacy')); // undefined
console.log(flags.has('legacy')); // true
console.log(flags.get('missing')); // undefined
console.log(flags.has('missing')); // false
if (flags.get('beta')) {
console.log('never runs'); // false is falsy, though the key exists
}Updating values
Map has no built-in "update" method. The usual approach is to read the value, compute the new one, and write it back. The ?? operator provides a default for missing keys without treating 0 as missing.
function countWords(text) {
const counts = new Map();
for (const word of text.toLowerCase().split(/\s+/)) {
if (word === '') continue;
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
const counts = countWords('The cat and the hat');
console.log(counts.get('the')); // 2
console.log(counts.get('dog')); // undefined
console.log(counts.size); // 4If the values are objects or arrays, you can change them in place after one lookup, and you don't need to call set again:
const groups = new Map();
function addTo(group, item) {
if (!groups.has(group)) {
groups.set(group, []);
}
groups.get(group).push(item);
}
addTo('fruit', 'apple');
addTo('fruit', 'pear');
console.log(groups.get('fruit')); // ['apple', 'pear']Object keys are compared by reference
Two objects with the same contents are two different keys. To find an object key, you need a reference to the same object.
const m = new Map();
const a = { id: 1 };
const b = { id: 1 };
m.set(a, 'first');
console.log(m.get(a)); // 'first'
console.log(m.get(b)); // undefined
console.log(m.get({ id: 1 })); // undefinedIf you need lookups by content, choose a primitive key such as a.id or a string you build from the fields. The exact equality rule, including how NaN and -0 behave, is covered in the SameValueZero chapter.
The bracket-notation trap
A Map is also an ordinary object, so bracket and dot assignment still work on it. They create regular properties on the Map object and do not add entries. get, has, size, and iteration all ignore those properties.
const m = new Map();
m['color'] = 'red';
console.log(m.size); // 0
console.log(m.get('color')); // undefined
console.log(m.has('color')); // false
console.log(m.color); // 'red', a plain property, not an entryThis mistake usually comes from converting object-based code to a Map and missing one assignment. Linters can't always catch it, so search for [ and . writes on any variable that holds a Map.
Common errors at a glance
| Mistake | Symptom | Fix |
|---|---|---|
| `map[key] = value` | `size` stays 0, `get` returns `undefined` | Use `map.set(key, value)` |
| `map.size()` | `TypeError: map.size is not a function` | Use `map.size` |
| `if (map.get(k))` for existence | Falsy values look missing | Use `map.has(k)` |
| Looking up a fresh object literal | Always `undefined` | Keep the original reference or use a primitive key |
| `new Map([1, 2])` | `TypeError` | Pass pairs: `new Map([[1, 'a'], [2, 'b']])` |
| Expecting `set` to move an existing key | Order unchanged | `delete` and then `set` |
Exercise
What does this code log, and why? const m = new Map([['x', 0]]); m.set('x', m.get('x') || 5); m['y'] = 1; console.log(m.get('x'), m.size);
Show answer
It logs "5 1". m.get('x') returns 0, which is falsy, so the || operator picks 5 and overwrites the stored value. Using ?? instead would have kept 0. The assignment m['y'] = 1 creates an ordinary property on the Map object and does not add an entry, so size stays 1.
Exercise
Write a function lastSeen(events) that takes an array of { user, time } objects, where user is an object reference, and returns a Map from each user object to the largest time seen for that user. Users must be matched by reference, not by contents.
Show answer
function lastSeen(events) { const result = new Map(); for (const { user, time } of events) { if (!result.has(user) || time > result.get(user)) { result.set(user, time); } } return result; } Using the user object itself as the key gives matching by reference. The has check handles the first event for each user, including the case where time is 0.
Exercise
Starting from const m = new Map([['a', 1], ['b', 2], ['c', 3]]), which calls make the key order b, c, a with a's value equal to 10?
Show answer
Call m.delete('a') and then m.set('a', 10). Calling only m.set('a', 10) would update the value but leave 'a' in first position, because overwriting an existing key keeps its original insertion position.