Maps accept arbitrary keys without string conversion. Ordinary object keys are strings or symbols. Choose according to key identity and collection operations.
Step-by-step walkthrough
Step 1: Choose a key identity
Determine whether keys are known record fields, external strings or actual object identities. An ordinary record fits named fields; a Map fits a dynamic collection of keyed entries. Neither choice automatically validates the values or establishes a cache lifetime.
Step 2: Follow conversion behavior
Ordinary property access converts nonsymbol keys to property keys, often strings. Map retains key identity. Two objects that describe the same ID are therefore different Map keys unless you deliberately use their stable ID as the key.
Step 3: Specify iteration and lifetime
A Map exposes collection size and insertion-order iteration, but it can grow without bounds. For a cache, define overwrite policy, expiration and removal. For an object dictionary, consider prototype behavior and own-property checks when accepting arbitrary keys.
Worked scenario
Two different objects are distinct Map keys. As ordinary object keys, both can become the same string.
const first = {id: 1};
const second = {id: 1};
const byObject = new Map([[first, 'first']]);
console.log(byObject.get(second)); // undefined
const byId = new Map([[first.id, first]]);
console.log(byId.get(second.id).id); // 1
console.log(byId.size); // 1Walk through the example
The first map indexes one specific object reference. The second map indexes the numeric business identifier, allowing separately received records to address the same entry. The intended overwrite behavior still needs a rule: a new record with that ID could replace the old one or be rejected as a conflict.
Common mistake
Map does not compare object contents; a newly created object cannot retrieve another object’s entry.
Verify the behavior
Test numeric and string IDs separately if both can arrive, repeated keys and deletion. Decide whether 1 and ‘1’ should be normalized into one domain ID before insertion. Inspect cache growth over repeated requests rather than only measuring successful lookups.
Interview exercise
Cache independent API records.
Answer and reasoning
Key a Map by stable record ID and specify expiration rather than relying on object identity.
Follow-up discussion
Is a Map always faster? Performance depends on workload, engine and access patterns. Select correct semantics first and measure representative behavior. Does Map solve prototype pollution? It avoids ordinary object-property key behavior for entries, but input validation and safe surrounding code are still necessary.
Continue learning
Compare the scenario with the JavaScript interview questions and test your understanding with the JavaScript MCQs. For terminology and implementation details, consult the reference material.