Glossary / Map
Map
Map stores key/value pairs in insertion order and allows keys of any JavaScript value type. Unlike plain objects, it does not coerce keys to strings or inherit application keys from Object.prototype. It is a useful choice for dynamic dictionaries, caches, and associations where key identity matters.
Key semantics and iteration
const cache = new Map();
const key = { id: 1 };
cache.set(key, "result");
cache.get(key); // "result"
cache.get({ id: 1 }); // undefined: different object identity
Map uses SameValueZero for key matching: NaN matches NaN, and +0/-0 are treated as the same key. Object and function keys compare by reference identity. Updating an existing key does not change its insertion position; deleting and re-adding appends it at the end. Map iteration (keys, values, entries, default iterator) follows insertion order.
The specification requires average access to be sublinear in collection size, not a specific hash-table implementation or guaranteed constant-time complexity. Map is not automatically faster than objects for every workload. Use object literals for fixed-shape records and Map for collection semantics. JSON does not serialize Map entries by default; define an explicit wire representation.
Interview questions
- How are object keys compared? By identity.
- Does Map coerce
1and"1"to the same key? No. - What is the iteration order? Insertion order.
- Does the spec guarantee O(1) access? No; it requires average sublinear access.
- Why choose Map over an object? Arbitrary keys, explicit size/iteration, and no accidental inherited key behavior.