Map: Flexible Key-Value DictionariesA 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.
Map ExampleNotice 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));
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").myMap.length: Just like Set, Map uses .size, not .length.JSON.stringify(myMap) directly: JSON.stringify(new Map([["a", 1]])) returns "{}"! Convert first with Object.fromEntries(myMap) or [...myMap].Map?Pass Object.entries(obj) into the constructor: const myMap = new Map(Object.entries(obj));.
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.
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.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.