0
0
JavascriptComparisonBeginner · 4 min read

Map vs WeakMap in JavaScript: Key Differences and Usage

In JavaScript, Map stores key-value pairs with keys of any type and keeps strong references to keys, preventing garbage collection. WeakMap only accepts objects as keys and holds weak references, allowing keys to be garbage collected when no other references exist.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of Map and WeakMap based on key features.

FeatureMapWeakMap
Key TypesAny value (objects, primitives)Only objects
Reference TypeStrong references to keysWeak references to keys
Garbage CollectionKeys are not garbage collected while in MapKeys can be garbage collected if no other references exist
IterableYes, supports iterationNo, not iterable
Use CaseGeneral key-value storageMemory-sensitive caches or private data
Methodsset, get, has, delete, clearset, get, has, delete (no clear)
⚖️

Key Differences

Map allows keys of any type, including primitives like strings or numbers, and keeps strong references to these keys. This means as long as the Map holds a key, that key will not be removed by JavaScript's garbage collector, even if there are no other references to it.

In contrast, WeakMap only accepts objects as keys and holds weak references to them. If there are no other references to a key object outside the WeakMap, the key and its associated value can be automatically removed by garbage collection. This makes WeakMap useful for cases where you want to associate data with objects without preventing their cleanup.

Another important difference is that Map is iterable, so you can loop over its entries, keys, or values. WeakMap is not iterable because its keys can disappear at any time due to garbage collection, so JavaScript does not allow enumerating its contents.

💻

Map Code Example

javascript
const map = new Map();
const objKey = { id: 1 };

map.set(objKey, 'Object Value');
map.set('name', 'Map Example');

console.log(map.get(objKey));
console.log(map.get('name'));

// Iterating over Map
for (const [key, value] of map) {
  console.log(key, ':', value);
}
Output
[object Object] : Object Value Map Example { id: 1 } : Object Value name : Map Example
↔️

WeakMap Equivalent

javascript
const weakMap = new WeakMap();
const objKey = { id: 1 };

weakMap.set(objKey, 'Object Value');

console.log(weakMap.get(objKey));

// weakMap is not iterable, so this would cause an error:
// for (const [key, value] of weakMap) { console.log(key, value); }
Output
Object Value
🎯

When to Use Which

Choose Map when you need to store key-value pairs with keys of any type and want to iterate over them or clear all entries easily. It is ideal for general-purpose collections where keys should stay as long as you keep them.

Choose WeakMap when you want to associate data with objects without preventing their garbage collection, such as caching or storing private data tied to object lifetimes. Use it when memory management is important and you don't need to iterate over keys.

Key Takeaways

Map holds strong references to keys of any type and supports iteration.
WeakMap holds weak references only to object keys, allowing garbage collection.
WeakMap is not iterable and only accepts objects as keys.
Use Map for general key-value storage and iteration.
Use WeakMap for memory-sensitive cases where keys should not prevent cleanup.