Lesson

JS Maps

10 min reading
Free Course

JavaScript Map: Flexible Key-Value Dictionaries

A JavaScript Map stores key-value pairs while remembering exact insertion order and allowing any type—including objects, numbers, or functions—as keys. Unlike plain objects, a Map provides an instant .size property and has zero prototype key collisions.

Map vs. Plain Object ({})

Feature Map Plain Object {}
Key types Any value (objects, numbers, strings) Strings and Symbols only
Entry count Instant map.size Object.keys(obj).length
Prototype collisions None Shares Object.prototype keys
JSON support Needs Object.fromEntries(map) Native JSON.stringify()

Use plain objects {} for fixed data records and JSON payloads. Choose Map for dynamic dictionaries, caches, frequency counters, and lookups where user input supplies the keys. Iterating a Map with for (const [k, v] of myMap) visits entries in exact insertion order without extra Object.entries() conversion.

Practical Map Example

Notice how set(), get(), has(), and delete() work consistently without conflicting with built-in methods like toString.

const wordCounts = new Map();
const words = ["api", "node", "api", "dom", "node", "api"];

for (const word of words) {
  wordCounts.set(word, (wordCounts.get(word) ?? 0) + 1);
}

console.log("Total unique words:", wordCounts.size);
console.log("Count of 'api':", wordCounts.get("api"));

// Convert Map back to plain object for JSON serialization
const asObject = Object.fromEntries(wordCounts);
console.log("Serialized:", JSON.stringify(asObject));

Common Mistakes to Avoid

  • Setting keys with bracket syntax (myMap["key"] = 1): Bracket notation attaches a plain object property to the Map instance instead of storing an entry inside the map! Always use myMap.set("key", 1) and myMap.get("key").
  • Checking myMap.length: Just like Set, Map uses .size, not .length.
  • Calling JSON.stringify(myMap) directly: JSON.stringify(new Map([["a", 1]])) returns "{}"! Convert first with Object.fromEntries(myMap) or [...myMap].

Frequently Asked Questions

How do I convert a plain object into a Map?

Pass Object.entries(obj) into the constructor: const myMap = new Map(Object.entries(obj));.

What does map.get(key) return if the key is missing?

It returns undefined, so combining it with nullish coalescing (map.get(key) ?? 0) makes counters and defaults very clean.

What is a WeakMap used for?

A WeakMap accepts only object keys and holds weak references, allowing garbage collection once the key object is no longer used elsewhere.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum