Skip to main content

WeakMap VS Map

The difference between Map and WeakMap in JavaScript is fundamental. Both store "key -> value" pairs, but WeakMap was created for special cases where you need to "attach data to objects" without interfering with the garbage collector (GC).


The main idea:

PropertyMapWeakMap
Keysany values (strings, numbers, objects)objects only
Reference typestrong (the object stays alive while a reference exists)weak (the GC can remove the object)
Iteration (for...of, .keys(), .size)yesno
Checking the size.sizeno
Usagegeneral-purpose key-value pairstemporary "attachments" to objects

Example with Map:

javascript
const map = new Map(); let user = { name: "Alice" }; map.set(user, "User"); console.log(map.get(user)); // "User" user = null; // remove the reference console.log(map); // Map still holds { name: "Alice" }

The object won't be removed from memory as long as Map holds a reference to it, which is a memory leak.


Now WeakMap:

javascript
const weakMap = new WeakMap(); let user = { name: "Alice" }; weakMap.set(user, "User"); console.log(weakMap.has(user)); // true user = null; // the object becomes unreachable // the object will be automatically removed by the garbage collector!
  • If an object is no longer reachable from the code, the garbage collector removes both the object itself and its entry in WeakMap.
  • WeakMap does not prevent memory cleanup.

What does a "weak reference" mean?

A "weak" reference is a reference that does not prevent the garbage collector from removing an object if there are no other "strong" references to it.

In a regular Map, keys are held "strongly": as long as the Map exists, all its keys and values stay in memory. In WeakMap they don't: the GC can clear them at any moment.


WeakMap methods:

MethodDescription
set(key, value)add a value for an object
get(key)retrieve a value
has(key)check whether an entry exists
delete(key)remove an entry

Missing: size, keys(), values(), entries(), forEach()

  • because WeakMap is not iterable.

Example of practical usage:

Storing private data for objects

javascript
const privateData = new WeakMap(); class User { constructor(name, age) { privateData.set(this, { age }); this.name = name; } getAge() { return privateData.get(this).age; } } const alice = new User("Alice", 30); console.log(alice.getAge()); // 30 // After alice is removed, the object and its private data disappear from memory
  • The private data isn't visible from the outside,
  • it gets cleaned up automatically when the object is removed.

Another example: caching

javascript
const cache = new WeakMap(); function getData(obj) { if (!cache.has(obj)) { const data = Math.random(); // suppose this is expensive to compute cache.set(obj, data); } return cache.get(obj); } let user = {}; console.log(getData(user)); // the cache entry is created user = null; // the object and its cache entry are automatically cleared

Ideal for temporarily storing computed data without memory leaks.


In short:

PropertyMapWeakMap
Key typeanyobjects only
Iterating elementsyesno
Relationship to objectsstrongweak
Automatic removalnoyes
Usagecache, dictionaries, configsprivate data, leak-free cache

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.