Understanding JavaScript WeakMap and WeakSet

JavaScript WeakMap and WeakSet

Originally published on Makemychance.com

In JavaScript, we often use collections like Map and Set to store data. But did you know there are special versions called WeakMap and WeakSet?

They’re called “weak” because they allow JavaScript’s garbage collector to automatically remove entries when they are no longer used — making your apps more memory-efficient.

Let’s explore what they are, how they work, and when to use them.


🧠 What is a WeakMap?

A WeakMap is a collection of key-value pairs, but only objects can be used as keys. These keys are held “weakly”, meaning if there’s no other reference to the key object, it gets garbage collected.

✅ Syntax

const weakMap = new WeakMap();

✅ Example

let user = { name: "Arsalan" };

const weakMap = new WeakMap();
weakMap.set(user, "Active");

console.log(weakMap.get(user)); // "Active"

user = null; // Now the object is eligible for garbage collection

After user = null, the object is no longer reachable, so both the key and its value in the WeakMap can be removed from memory automatically.


⚠️ Limitations of WeakMap

  • You can’t iterate over it (no .forEach, .keys(), etc.).
  • You can’t check its size.
  • Only object keys are allowed.

🧱 Use Case

Use WeakMap when:

  • You want to store private data tied to objects.
  • You want automatic cleanup when the object is no longer in use.

🧠 What is a WeakSet?

A WeakSet is similar to a Set, but it only stores objects, and those objects are held weakly (just like keys in a WeakMap).

✅ Syntax

const weakSet = new WeakSet();

✅ Example

let user = { name: "Arsalan" };

const weakSet = new WeakSet();
weakSet.add(user);

console.log(weakSet.has(user)); // true

user = null; // user object will be garbage collected

⚠️ Limitations of WeakSet

  • Only objects allowed (no strings, numbers, etc.)
  • Can’t iterate (no forEach, for...of, etc.)
  • No .size or .clear() methods

🔍 WeakMap vs WeakSet – Quick Comparison

FeatureWeakMapWeakSet
StoresKey-value pairsOnly objects
Keys/ItemsOnly objectsOnly objects
Iterable?❌ No❌ No
Garbage Collected?✅ Yes (if no reference)✅ Yes (if no reference)

🌐 Browser Compatibility

Fully supported in all modern browsers:

✅ Chrome
✅ Firefox
✅ Safari
✅ Edge


✅ Final Thoughts

Both WeakMap and WeakSet are useful when dealing with temporary object associations. They allow you to store data without preventing cleanup, which is great for improving performance in complex applications.

They’re not used in every project, but when you’re building large-scale apps or libraries — especially where memory management matters — they can be very helpful.


🔧 Pro Tip:
Use WeakMap to store private metadata about DOM elements or class instances. It’s a clean and safe approach!


💬 Want more practical JavaScript examples? Visit Makemychance.com for easy-to-follow guides.