Sub topic 7
When to Use a Map Instead of an Object
This chapter assumes you know how to create a Map and call set, get, has, and delete. It also assumes you have used plain objects as lookup tables. Both structures store key-value pairs, but they behave differently in ways that cause real bugs. The goal here is to recognize those differences and pick the right structure on purpose.
Keys Are Coerced to Strings in Objects
A plain object's property keys can only be strings or symbols. If you use any other value as a key, JavaScript first converts it to a string. That conversion makes every plain object key collapse into the same string, '[object Object]'.
const keyA = { id: 1 };
const keyB = { id: 2 };
const obj = {};
obj[keyA] = 'first';
obj[keyB] = 'second';
console.log(Object.keys(obj)); // ['[object Object]']
console.log(obj[keyA]); // 'second' (overwritten)
const map = new Map();
map.set(keyA, 'first').set(keyB, 'second');
console.log(map.get(keyA)); // 'first'
console.log(map.size); // 2Numbers get the same treatment, so obj[1] and obj['1'] refer to the same property. A Map keeps 1 and '1' as separate keys.
Inherited Keys Leak Into Lookups
A plain object inherits from Object.prototype, so some keys look present before you add anything. This breaks counting code when the input comes from users.
const words = ['toString', 'hello', 'hello'];
const objCounts = {};
for (const w of words) {
objCounts[w] = (objCounts[w] || 0) + 1;
}
console.log(typeof objCounts.toString); // 'string' (the inherited function plus 1)
const mapCounts = new Map();
for (const w of words) {
mapCounts.set(w, (mapCounts.get(w) ?? 0) + 1);
}
console.log(mapCounts.get('toString')); // 1
console.log(mapCounts.get('hello')); // 2Object.create(null) creates an object with no prototype and avoids this problem. You still get string-only keys, though, and no size.
Order and Size
A Map iterates in insertion order with no exceptions. Objects list integer-like keys first in ascending numeric order, then string keys in insertion order.
const o = { b: 1, 2: 'x', a: 2, 1: 'y' };
console.log(Object.keys(o)); // ['1', '2', 'b', 'a']
const m = new Map([['b', 1], [2, 'x'], ['a', 2], [1, 'y']]);
console.log([...m.keys()]); // ['b', 2, 'a', 1]To count a Map's entries you read map.size. For an object you call Object.keys(obj).length, which builds a new array on every call. Engines also tune Maps for frequent additions and deletions, while objects are tuned for a fixed set of properties.
Side-by-Side Comparison
| Concern | Plain object | Map |
|---|---|---|
| Key types | Strings and symbols only | Any value |
| Inherited keys | Yes, unless `Object.create(null)` | None |
| Iteration order | Integer-like keys first | Insertion order |
| Entry count | `Object.keys(obj).length` | `map.size` |
| Frequent add/delete | Slower in many engines | Designed for it |
| JSON support | Native | Needs conversion |
| Literal syntax and destructuring | Yes | No |
Rule of Thumb
Use an object for a record with a known, fixed shape, such as a config or an API payload, where you want dot access and JSON. Use a Map for a dictionary whose keys come from data at runtime, whose keys are not strings, or whose entries change often.
Exercise
You store a score per DOM element and also look up scores by user-entered nicknames, including names like "constructor". Which structure fits each job, and why?
Show answer
Use a Map for both. DOM elements are objects, so an object would coerce every element key to the same string. User nicknames can match inherited names like "constructor", which a plain object already appears to contain. A Map compares the actual key values and has no inherited entries.
Exercise
What does Object.keys({ z: 1, 10: 2, 3: 3 }) return?
Show answer
['3', '10', 'z']. Integer-like keys come first in ascending numeric order, then string keys in insertion order.