What is the difference between Map and WeakMap in JavaScript?
The Map
and WeakMap
in JavaScript are both used for storing key-value pairs, but they have key differences in their functionality and use cases.
1. Key Types
Map
: Keys can be of any data type, including primitive values and objects.WeakMap
: Keys must be objects. Primitive values (like strings or numbers) are not allowed as keys.
2. Garbage Collection
Map
: Keeps strong references to keys, meaning the key-value pair remains in memory until it is explicitly removed.WeakMap
: Keys are held weakly, meaning they are subject to garbage collection if there are no other references to the key object
3. Iteration
Map
: Supports iteration methods such as.keys()
,.values()
,.entries()
, and is iterable using afor...of
loopWeakMap
: Does not support iteration or methods to retrieve all keys, values, or entries. This ensures privacy and security for the data stored
Use Cases
Map
:
- General-purpose key-value storage.
- When you need all the data to persist and want to iterate over it.
WeakMap
:
- Useful for associating private data with objects (e.g., metadata, caching).
- When you want the key-value pair to be automatically removed when the key object is no longer in use.
const cache = new WeakMap();
function getCachedData(obj) {
if (!cache.has(obj)) {
cache.set(obj, { data: "Expensive computation result" });
}
return cache.get(obj);
}
let obj = {};
console.log(getCachedData(obj)); // { data: "Expensive computation result" }
obj = null; // When `obj` is garbage collected, the cache is cleared too.