No Login Data Private Local Save

WeakMap & WeakSet Demo - Online Garbage‑Collected Collections

7
0
0
0

WeakMap & WeakSet Demo

Garbage-Collected Collections

Explore JavaScript's weakly-held collections — understand garbage collection, weak references, and how WeakMap & WeakSet help prevent memory leaks in real-world applications.

WeakMap Demo

Key → Value (keys must be objects)
No objects created yet. Use the input below.
Operation Log
--:--WeakMap initialized. Create an object to begin.

WeakSet Demo

Object membership tracking (objects only)
No objects created yet. Use the input below.
Operation Log
--:--WeakSet initialized. Create an object to begin.

Garbage Collection Detection FinalizationRegistry

Observe when released objects are garbage collected
Waiting for GC...
No tracked objects. Create one above.
GC Event Log
--:--GC monitor ready. Create and release objects to observe garbage collection.

Map vs WeakMap & Set vs WeakSet — Full Comparison

Feature Map WeakMap Set WeakSet
Key / Value Type Any type Keys: Objects only Any type Values: Objects only
Iterable Yes No Yes No
.size property Yes No Yes No
.clear() method Yes No Yes No
Key references Strong Weak (GC-friendly) Strong Weak (GC-friendly)
Prevents GC of keys Yes (risk of leak) No Yes (risk of leak) No
Common Use Case General key-value storage Object metadata, caches, private data Unique value collections Object tagging / "processed" markers

Practical Code Examples

Real-world patterns using WeakMap & WeakSet
// WeakMap: Store DOM element metadata without memory leaks
const elementData = new WeakMap();

function attachData(el, data) {
  elementData.set(el, data);
}

function getData(el) {
  return elementData.get(el);
}

// When the DOM element is removed, its WeakMap entry
// becomes eligible for garbage collection automatically.
// No manual cleanup needed — no memory leak!

Frequently Asked Questions

Everything you need to know about WeakMap & WeakSet
What is the main difference between Map and WeakMap?

The fundamental difference lies in how they hold references to their keys:

  • Map holds strong references to keys. As long as a Map exists, its keys cannot be garbage collected — even if nothing else references those keys. This can cause memory leaks.
  • WeakMap holds weak references to keys. If a key object has no other references outside the WeakMap, it becomes eligible for garbage collection. The WeakMap entry is automatically removed when the key is GC'd.

Because of weak references, WeakMap keys must be objects (not primitives), and WeakMaps are not iterable — you cannot enumerate their contents because entries may disappear at any time.

Why can't WeakMap / WeakSet be iterated?

WeakMap and WeakSet are non-iterable by design. The reason is tied to garbage collection:

  • Since entries can be garbage collected at any time (non-deterministically), the result of iteration would be unpredictable.
  • If JavaScript exposed iteration, it would require knowing exactly which entries exist at a given moment — which conflicts with the weak reference model.
  • This also prevents attackers from inspecting weakly-held data they shouldn't have access to.

The lack of iteration is not a limitation — it's a feature that ensures weak references remain truly weak and GC-friendly.

Why do WeakMap and WeakSet have no .size property?

For the same reason they're not iterable: the size is non-deterministic. Entries can be garbage collected at any time, so the count would constantly change in ways that JavaScript can't reliably track. Exposing a .size would give a false sense of precision. If you need to know the size or iterate entries, use a regular Map or Set instead.

What are the best use cases for WeakMap?

WeakMap excels in scenarios where you need to associate data with objects without preventing their garbage collection:

  1. DOM Element Metadata — Store data about DOM elements. When the element is removed from the DOM, the associated data is automatically cleaned up.
  2. Private Instance Data — Implement truly private properties in classes (used by many frameworks).
  3. Caching — Cache computed results keyed by object. When the object is no longer needed, the cache entry disappears.
  4. Vue 3 Reactivity — Vue 3's composition API uses WeakMap internally to track reactive dependencies without memory leaks.
What are the best use cases for WeakSet?

WeakSet is ideal for tagging or marking objects:

  1. "Already Processed" Markers — Track which objects have been processed without preventing their GC.
  2. Duplicate Prevention — Ensure an object isn't added to a collection twice.
  3. Membership Testing — Check if an object belongs to a set without holding a strong reference.
  4. Event Listener Tracking — Track which DOM elements already have listeners attached (cleanup is automatic when elements are removed).
How does garbage collection work with WeakMap / WeakSet?

JavaScript engines use mark-and-sweep garbage collection. Here's how it interacts with weak collections:

  • The GC starts from "root" references (global objects, stack variables) and marks all reachable objects.
  • Objects only referenced by WeakMap keys or WeakSet values are not considered reachable — the weak reference doesn't count.
  • During the sweep phase, unreachable objects are freed, and their WeakMap/WeakSet entries are automatically removed.

Important: GC timing is non-deterministic. You cannot predict exactly when an object will be collected. Use FinalizationRegistry to get callbacks when specific objects are GC'd.

Can WeakMap prevent memory leaks in my application?

Yes, absolutely. WeakMap and WeakSet are specifically designed to prevent a common class of memory leaks:

  • Without WeakMap, if you use a regular Map to store data keyed by DOM elements, those elements can never be garbage collected — even after they're removed from the DOM — because the Map holds a strong reference.
  • With WeakMap, the DOM element can be garbage collected when removed, and the associated data is automatically cleaned up.

This is why frameworks like Vue 3, Svelte, and modern libraries use WeakMap extensively for internal bookkeeping.

Is FinalizationRegistry reliable for detecting GC?

FinalizationRegistry provides callbacks when registered objects are garbage collected, but with important caveats:

  • No timing guarantee — The callback may fire much later than when the object becomes unreachable.
  • Best-effort — The engine may not call the callback at all in some cases (e.g., during page shutdown).
  • Not for critical logic — Never rely on it for essential application logic. Use it for debugging, monitoring, or cleanup of non-critical resources.

It's a useful diagnostic tool but not a substitute for proper memory management.

Which browsers support WeakMap and WeakSet?

Both WeakMap and WeakSet have excellent browser support:

  • WeakMap: All modern browsers including Chrome 36+, Firefox 6+, Safari 8+, Edge 12+, and IE 11+.
  • WeakSet: Chrome 36+, Firefox 34+, Safari 9+, Edge 12+. (Not supported in IE 11.)
  • FinalizationRegistry: Chrome 84+, Firefox 79+, Safari 14.1+, Edge 84+. This is a newer API.

WeakMap and WeakSet are safe to use in production without polyfills for virtually all modern web applications.