Sub topic 7
When to Use a Map Instead of an Object
This chapter assumes you know the Map API from earlier chapters (set, get, has, delete, size), how Maps iterate in insertion order, and how SameValueZero compares keys. It also assumes you are comfortable with object property access, Object.keys, and the difference between primitives and object references.
For years, plain objects were the only built-in key-value store JavaScript had, and they still work well for many jobs. They also have several quirks that make them a poor dictionary. This chapter covers those quirks one at a time, and then gives you a rule for deciding which structure to use.
Records Versus Dictionaries
It helps to separate two ways of using key-value data.
- A record has a fixed set of known fields, such as
{ name, email, age }. You know the keys when you write the code, and each field may hold a different type. - A dictionary has keys that come from data at runtime, such as user IDs, words in a document, or DOM nodes. The keys are not known in advance, entries come and go, and every value usually has the same type.
Objects are designed for records. Map is designed for dictionaries. Most of the problems below show up when you use an object as a dictionary.
Key Types: Coercion to Strings
Object property keys can only be strings or symbols. Any other key is converted to a string first. Two different objects used as keys both become '[object Object]' and silently overwrite each other.
const a = { id: 1 };
const b = { id: 2 };
const obj = {};
obj[a] = 'first';
obj[b] = 'second';
console.log(Object.keys(obj)); // ['[object Object]']
console.log(obj[a]); // 'second' (a's entry was overwritten)
const map = new Map();
map.set(a, 'first').set(b, 'second');
console.log(map.get(a)); // 'first'
console.log(map.size); // 2Numbers are coerced in the same way, so obj[1] and obj['1'] are the same property. In a Map, 1 and '1' are separate keys because SameValueZero does not convert types.
const obj = {};
obj[1] = 'number';
obj['1'] = 'string';
console.log(Object.keys(obj).length); // 1
const map = new Map([[1, 'number'], ['1', 'string']]);
console.log(map.size); // 2If your keys are objects, or if mixing up numbers and strings would cause a bug, use a Map.
Inherited Keys and the Prototype
A plain object created with {} inherits from Object.prototype. As a result, it already "contains" keys such as toString, constructor, and hasOwnProperty before you add anything. Code that looks up keys from user data can hit these by accident.
const counts = {};
function countWord(word) {
counts[word] = (counts[word] || 0) + 1;
}
countWord('hello');
countWord('constructor');
console.log(counts.hello); // 1
console.log(typeof counts.constructor); // 'string'
console.log(counts.constructor); // 'function Object() { [native code] }1'The lookup counts['constructor'] found the inherited Object function, which is truthy. The code then added 1 to it, and that concatenated the function's source text with '1'.
The key '__proto__' is worse. On an ordinary object, assigning to it changes the object's prototype instead of creating an entry, and assigning a string to it is ignored without any error.
const obj = {};
obj['__proto__'] = 'value';
console.log(Object.keys(obj)); // []
const map = new Map();
map.set('__proto__', 'value');
console.log(map.get('__proto__')); // 'value'A Map has no inherited entries. map.get('constructor') returns undefined until you set that key yourself.
There are workarounds for objects. Object.create(null) makes an object with no prototype, so __proto__ and constructor become ordinary keys. Object.hasOwn(obj, key) checks only own properties. Both work, but every part of the code has to remember to use them, and a Map gives you the same safety by default.
const safe = Object.create(null);
safe['constructor'] = 1;
safe['__proto__'] = 2;
console.log(Object.keys(safe)); // ['constructor', '__proto__']Iteration Order
Both structures have a defined order, but the rules are different. A Map always iterates in insertion order. Object property order puts integer-like keys first, in ascending numeric order, then string keys in insertion order, then symbols.
const obj = { b: 1, 2: 'two', a: 2, 1: 'one' };
console.log(Object.keys(obj)); // ['1', '2', 'b', 'a']
const map = new Map([['b', 1], [2, 'two'], ['a', 2], [1, 'one']]);
console.log([...map.keys()]); // ['b', 2, 'a', 1]If insertion order matters, for example a list of recently used items or IDs in the order they arrived, an object with numeric IDs reorders them. A Map keeps them as inserted.
Objects also cannot be iterated directly with for...of. You have to go through Object.keys, Object.values, or Object.entries, and each call builds a new array. A Map is iterable as it is.
Size and Frequent Changes
map.size is a property that is always up to date. Counting an object's entries with Object.keys(obj).length builds an array of every key each time you ask.
Engines also optimize the two structures for different workloads. V8 and other engines speed up objects by assuming they keep a stable shape. When an object gets many keys added and deleted, the engine often switches it to a slower internal dictionary mode. Map is built for frequent additions and removals. The size of the difference depends on the engine and the workload, so measure before you rewrite code that is already fast enough. For a large dictionary that changes often, though, Map is the safer default.
The Bracket Assignment Gotcha
A Map is also an object, so bracket syntax works on it without any error. It sets a property on the Map object itself and does not create an entry.
const m = new Map();
m['x'] = 1;
console.log(m.has('x')); // false
console.log(m.size); // 0
console.log(m.x); // 1 (a plain property, not an entry)This bug often appears when code is converted from objects to Maps and some lookups are missed. Always use set and get.
Where Objects Still Win
Objects are the better choice for records:
- Property syntax is short:
user.name, destructuring withconst { name } = user, optional chaining withuser?.address?.city, and spread with{ ...defaults, ...overrides }. JSON.stringifyserializes objects directly. A Map needs a conversion step, which a later chapter covers.- Engines optimize objects with a fixed shape very well.
- Type systems such as TypeScript describe fixed fields more precisely with object types.
- Objects can have methods and work with
this, classes, and getters.
Comparison Summary
| Concern | Plain object | Map |
|---|---|---|
| Key types | Strings and symbols only; others coerced | Any value, compared with SameValueZero |
| Inherited keys | Yes, from `Object.prototype` unless created with `Object.create(null)` | None |
| Iteration order | Integer-like keys first, then insertion order | Pure insertion order |
| Direct `for...of` | No | Yes |
| Entry count | `Object.keys(obj).length` | `map.size` |
| Frequent add/delete | May fall back to slower dictionary mode | Designed for it |
| JSON | Native | Needs conversion |
| Syntax | Dot access, destructuring, spread | Method calls |
A Decision Flow
A short version of the rule: use an object when the keys are part of your program, and use a Map when the keys are part of your data.
Exercise
A function counts how often each word appears in user-submitted text using const counts = {} and counts[word] = (counts[word] || 0) + 1. Name two inputs that break it and rewrite the counter with a Map.
Show answer
The word "constructor" (or "toString") breaks it because the lookup finds an inherited function and the addition concatenates text onto it. The word "_proto_" also breaks it, because the assignment goes to the prototype setter and no count is stored. A Map version: const counts = new Map(); function countWord(word) { counts.set(word, (counts.get(word) ?? 0) + 1); }. A Map has no inherited entries, so every word is stored as a normal key.
Exercise
What do these lines print, and why? const m = new Map(); m['a'] = 1; m.set('b', 2); console.log(m.size, m.has('a'), Object.keys(m));
Show answer
It prints 1 false ['a']. Bracket assignment created an ordinary property named a on the Map object, which is not an entry, so size counts only b and has('a') is false. Object.keys lists own properties, so it shows 'a', not the Map's entries.
Exercise
You store orders by numeric ID as they arrive (IDs 30, 5, 12) and need to display them in arrival order. Would an object keyed by ID work? Which structure should you use?
Show answer
No. Object iteration puts integer-like keys in ascending numeric order, so it would show 5, 12, 30. A Map iterates in insertion order and shows 30, 5, 12, and it keeps the IDs as numbers instead of converting them to strings.