01 / 21
{ } Map

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.

JavaScript

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).

const user = { name: "Alice", age: 17, isStudent: true }; // Keys are always strings under the hood

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.

const scores = new Map(); scores.set("Alice", 95); scores.set(42, "the answer"); scores.set(true, "yes"); // Keys keep their original type

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.

Key Coercion Bugs
Object silently converts numeric keys to strings, creating surprising equality failures.
Performance at Scale
Map is optimized for frequent additions and deletions: up to 2x faster in hot loops.
API Clarity
Map's dedicated methods (.get, .set, .has) signal intent better than bracket notation.

The Core Decision Rule

Are keys known at write time? YES NO Object { } Map Non-string keys or frequent add/delete? MAYBE YES NO

Key Types: The Critical Difference

// Object: keys are always coerced to strings const obj = {}; obj[1] = "one"; obj["1"] = "string one"; console.log(obj[1]); // "string one" — collision! // Map: keys preserve their type const map = new Map(); map.set(1, "one"); map.set("1", "string one"); console.log(map.get(1)); // "one" — no collision

Object vs. Map: Side by Side

Feature Object { } Map
Key typesString or Symbol onlyAny value
Insertion orderMostly preserved (edge cases)Always guaranteed
SizeManual: Object.keys(o).lengthBuilt-in: .size
Iterationfor...in / Object.entriesfor...of / .forEach
Prototype pollutionPossible (inherits from Object)Not possible
JSON supportNativeNeeds manual conversion
Frequent add/deleteSlowerOptimized

Built-in .size and Clean Iteration

// Object — clunky size check const obj = { a: 1, b: 2, c: 3 }; console.log(Object.keys(obj).length); // 3 // Map — instant property const map = new Map([["a",1],["b",2],["c",3]]); console.log(map.size); // 3

How to Decide: Step by Step

1
Identify your keys. Are they always strings you define in your source code? If yes, lean Object.
2
Check key types. Will any key be a number, boolean, DOM element, or object? If yes, you need Map.
3
Consider mutation frequency. Adding and deleting keys often? Map is optimized for this.
4
Think about serialization. Need to send the data as JSON? Object works natively.
5
Watch for prototype keys. Need guaranteed clean lookup with no inherited properties? Map is safer.

Example 1: User Profile

You are building a user profile with fixed, known fields. The data will be sent to an API as JSON.

// ✓ Object is the right choice const profile = { username: "alice_dev", email: "alice@example.com", age: 17, isVerified: true }; JSON.stringify(profile); // works natively

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.

// ✓ Map is the right choice const tooltips = new Map(); document.querySelectorAll(".btn").forEach(btn => { tooltips.set(btn, { text: btn.dataset.tip, visible: false }); }); // Later, retrieve by the element itself: tooltips.get(someButton).visible; // false

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.

// ✓ Map is the right choice function countWords(text) { const freq = new Map(); for (const word of text.split(" ")) { freq.set(word, (freq.get(word) || 0) + 1); } return freq; }

The Prototype Trap

const obj = {}; // "constructor" exists on every object by default! console.log(obj.constructor); // ƒ Object() — not undefined! // Checking "hasOwnProperty" as a key is risky too obj["toString"] = "hello"; console.log(obj + ""); // TypeError! // Map has no inherited keys const map = new Map(); map.has("constructor"); // false — clean

The Object.create(null) Workaround

You can create a "bare" object with no prototype, but it comes with trade-offs.

const bare = Object.create(null); bare["constructor"] = "safe"; // Works! No prototype interference. // But you lose convenience methods: bare.hasOwnProperty; // undefined bare.toString; // undefined

Common Mistakes

Using Object for dynamic keys
When keys come from user input, Object risks prototype collisions and key coercion.
Using Map when you need JSON
Map doesn't serialize to JSON natively. If the API expects JSON, Object is simpler.
Checking Map size with .length
Maps use .size, not .length. Calling .length returns undefined.
Using bracket notation on Map
Writing map["key"] sets a property on the Map object itself, not inside the Map's data store. Use .set() and .get().

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?