Object vs. Map
Learn when to reach for a plain Object and when a Map is the right tool: key types, performance, and iteration order demystified.
What Is a Plain Object?
An Object is JavaScript's original key-value structure. You create one with curly braces { }, and every key is automatically converted to a string (or Symbol).
What Is a Map?
A Map is a dedicated key-value collection introduced in ES6. Unlike Object, a Map can use any value as a key: objects, functions, numbers, even NaN.
Why Does the Choice Matter?
Using the wrong data structure leads to subtle bugs, slower performance, and harder-to-read code. Understanding the trade-offs helps you write professional-grade JavaScript.
The Core Decision Rule
Key Types: The Critical Difference
Object vs. Map: Side by Side
| Feature | Object { } | Map |
|---|---|---|
| Key types | String or Symbol only | Any value |
| Insertion order | Mostly preserved (edge cases) | Always guaranteed |
| Size | Manual: Object.keys(o).length | Built-in: .size |
| Iteration | for...in / Object.entries | for...of / .forEach |
| Prototype pollution | Possible (inherits from Object) | Not possible |
| JSON support | Native | Needs manual conversion |
| Frequent add/delete | Slower | Optimized |
Built-in .size and Clean Iteration
How to Decide: Step by Step
Example 1: User Profile
You are building a user profile with fixed, known fields. The data will be sent to an API as JSON.
Example 2: DOM Element Cache
You need to store metadata for DOM elements that users interact with. The keys are actual HTML elements, not strings.
Example 3: Word Frequency Counter
Count how many times each word appears in user input. Keys are dynamic (determined at runtime), and entries are frequently added.
The Prototype Trap
The Object.create(null) Workaround
You can create a "bare" object with no prototype, but it comes with trade-offs.
Common Mistakes
Quick-Reference Summary
| Scenario | Use Object | Use Map |
|---|---|---|
| Fixed config / settings | ✓ | |
| JSON serialization needed | ✓ | |
| Non-string keys | ✓ | |
| Frequent add/delete | ✓ | |
| Need guaranteed iteration order | ✓ | |
| Need .size property | ✓ | |
| Keys from user input | ✓ | |
| Destructuring / spread | ✓ |
Question 1 of 5
You need to store metadata using DOM elements as keys. Which data structure should you use?
Question 2 of 5
What happens when you set obj[1] = "a" and then obj["1"] = "b" on a plain Object?
Question 3 of 5
You're building a REST API response that must be serialized to JSON. Which structure is most appropriate?
Question 4 of 5
A developer writes map["score"] = 100 instead of map.set("score", 100). What happens?
Question 5 of 5
Why is a plain Object risky when keys come from untrusted user input?