Object vs Map: When Objects Fall Short
You'll learn when plain objects become problematic as key-value stores and why Maps were introduced to JavaScript.
Why Objects Aren't Perfect for All Collections
For years, JavaScript developers used plain objects {} as key-value stores. While this works in simple cases, objects have hidden quirks that make them awkward for certain collection needs:
Key type limitations: Object keys are always converted to strings (or symbols). If you try to use a number or object as a key, JavaScript silently stringifies it:
const obj = {};
obj[1] = 'one';
obj[2] = 'two';
console.log(Object.keys(obj)); // ['1', '2'] — strings, not numbers!
Prototype pollution: Objects inherit properties from Object.prototype. Keys like toString or constructor can collide with inherited properties, causing unexpected behavior.
No built-in size: You need Object.keys(obj).length to count properties—inefficient and clunky.
Iteration awkwardness: There's no simple, direct way to iterate over just the data you stored without worrying about inherited properties.
When Maps Shine
Maps solve these issues by being purpose-built for key-value storage:
- Any key type: Use objects, functions, numbers—anything—as keys without conversion
- Clean structure: No prototype chain interference
- Built-in size: Just use
map.size - Natural iteration: Guaranteed insertion order with simple
.forEach(),keys(),values(), andentries()
Think of objects as Swiss Army knives (good for general structure) and Maps as specialized toolboxes (designed specifically for storing and retrieving pairs).
Key Takeaway: Use objects for structured data with known properties; use Maps when you need true key-value collection behavior with flexible keys and clean iteration.