Suggest an editImprove this articleRefine the answer for “How do WeakMap and WeakSet help the garbage collector?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**`WeakMap`** and **`WeakSet`** hold objects through weak references, so if an object is no longer used anywhere else, the garbage collector can remove it from memory even though it is still a key in a `WeakMap` or an entry in a `WeakSet`. **Key point:** regular `Map` and `Set` hold strong references and block the GC from freeing memory while the object remains in the collection.Shown above the full answer for quick recall.Answer (EN)Image## Reminder: how the garbage collector works JavaScript uses **automatic memory management**: the developer does not free memory manually. An object stays in memory **as long as there is at least one reference to it**. When no references remain → the **garbage collector (GC)** removes it. Example: ```javascript let user = { name: "Tim" }; // an object in memory user = null; // the reference is lost -> the object is removed by the GC ``` --- ## The problem with regular collections (`Map`, `Set`) Regular `Map` and `Set` **hold references** to objects **strongly (strong reference)**. Even if the object is no longer used anywhere else, the GC **cannot remove it** while it is inside a `Map` or `Set`. ```javascript let user = { name: "Tim" }; const map = new Map(); map.set(user, "data"); user = null; // the object is still stored in map! // the GC cannot free the memory ``` The result is a **memory leak** if there are a lot of such objects. --- ## The solution: WeakMap and WeakSet ### `WeakMap` - Keys are **objects only** (not strings, not numbers); - Values can be anything; - References are **"weak" (weak references)**: if the object is no longer used anywhere else, it is **automatically removed from the WeakMap by the garbage collector**. ```javascript let user = { name: "Tim" }; const weakMap = new WeakMap(); weakMap.set(user, "data"); user = null; // the object is no longer reachable // the GC will remove both the key and the value from the WeakMap automatically ``` After the object is removed from memory, the key **disappears** from the WeakMap. No manual `delete()` is needed. --- ### `WeakSet` - Stores **objects only** (no primitives); - Every entry is a **weak reference**; - If an object is no longer used anywhere else, it **gets removed from the WeakSet** automatically. ```javascript let user = { name: "Tim" }; const weakSet = new WeakSet(); weakSet.add(user); user = null; // the object is removed by the GC // weakSet automatically loses this reference ``` --- ## Key features of WeakMap / WeakSet | Property | WeakMap | WeakSet | |---|---|---| | Keys | Objects only | Objects only | | Values | Any | No values | | References | Weak | Weak | | GC clears automatically | Yes | Yes | | Can iterate (for...of) | No | No | | Methods | `set`, `get`, `has`, `delete` | `add`, `has`, `delete` | --- ## Why you cannot iterate a WeakMap / WeakSet Because the browser **does not know** when the GC will remove a specific object. The GC runs unpredictably, and the contents of such collections can change **at any moment**. That's why WeakMap and WeakSet **have no methods** like: - `.size` - `.keys()` - `.entries()` - `.values()` - `forEach` --- ## Real usage examples ### 1. Storing data "tied" to an object ```javascript const cache = new WeakMap(); function getUserData(user) { if (!cache.has(user)) { cache.set(user, { name: user.name, time: Date.now() }); } return cache.get(user); } let tim = { name: "Tim" }; console.log(getUserData(tim)); // cache the data tim = null; // the GC removes the object and its data from the cache ``` Here we avoided a memory leak: as soon as the user disappears from memory, their cache entry is cleared automatically. --- ### 2. Tracking object state ```javascript const visited = new WeakSet(); function process(obj) { if (visited.has(obj)) return; // already processed visited.add(obj); // ...do something } ``` After `obj` is removed from memory, it disappears from the `WeakSet` on its own. --- ## Comparison with regular collections | Type | Stores objects? | GC auto-cleanup | Can iterate | |---|---|---|---| | `Map` | Yes | No | Yes | | `WeakMap` | Yes | Yes | No | | `Set` | Yes | No | Yes | | `WeakSet` | Yes | Yes | No | --- ## Summary | Item | Description | |---|---| | Problem | Regular collections prevent the GC from removing unused objects | | Solution | `WeakMap` and `WeakSet` use weak references | | Behavior | Objects are removed from the collection automatically during garbage collection | | Limitations | Cannot iterate, get the size, or list the elements | | Usage | Caches, temporary data, visited flags, storing metadata |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.