Suggest an editImprove this articleRefine the answer for “WeakSet in JavaScript”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**`WeakSet` is a lightweight version of `Set` that stores only objects and holds them by a weak reference** (hence the word *Weak*). It is meant for cases where you want to keep unique objects but do not want to stop the garbage collector (GC) from removing them once nothing else references them. Primitives cannot be added, that throws a `TypeError`. It exposes only three methods, `add`, `delete` and `has`, while `size`, `forEach`, `keys`, `values` and `entries` are missing, because a `WeakSet` is not iterable. ```javascript const ws = new WeakSet(); let obj = { name: 'Alice' }; ws.add(obj); console.log(ws.has(obj)); // true obj = null; // the object becomes unreachable, GC drops it together with the entry ``` **Key point:** a collection of unique objects held weakly, perfect for "already processed" marks and a temporary cache, but unsuitable for permanent storage or iteration.Shown above the full answer for quick recall.Answer (EN)Image**`WeakSet` is a "lightweight" version of `Set` that stores only objects and holds them by a weak reference**, which is where the word *Weak* comes from. It is designed for situations where you want to keep unique objects around but must not prevent the garbage collector (GC) from removing them once they are no longer used anywhere else. ## Theory ### TL;DR - `WeakSet` stores **objects only**, primitives throw a `TypeError`. - References to its elements are **weak**: the GC may remove an object while it still sits in the collection. - Only three methods exist: `add(value)`, `delete(value)`, `has(value)`. - There is no `size`, `forEach`, `keys`, `values` or `entries`, because the collection **cannot be iterated**. - Elements are unique, exactly like in a `Set`. - Typical uses: "already processed" marks, a temporary cache, private data. ### Quick example ```javascript const ws = new WeakSet(); const obj1 = { name: 'Alice' }; const obj2 = { name: 'Bob' }; ws.add(obj1); ws.add(obj2); console.log(ws.has(obj1)); // true ``` What matters here: - The collection stores **objects only**, not primitives. Trying to add a string or a number fails immediately. ```javascript ws.add(123); // TypeError: Invalid value used in weak set ``` - If `obj1` is no longer used anywhere, the garbage collector **removes it automatically** and the entry disappears from the `WeakSet`. ### WeakSet methods | Method | Description | Example | | --- | --- | --- | | `add(value)` | adds an object | `ws.add(obj)` | | `delete(value)` | removes an object | `ws.delete(obj)` | | `has(value)` | checks for presence | `ws.has(obj)` | Note that **there are no** `size`, `forEach`, `keys`, `values` or `entries` methods, because a `WeakSet` **cannot be iterated**. That is not a whim of the specification: the GC removes elements at an unpredictable moment, so any iteration would produce a non deterministic result. ### The main difference from Set | Property | `Set` | `WeakSet` | | --- | --- | --- | | Can store primitives | Yes | No, objects only | | Elements are weakly held (GC may remove them) | No | Yes | | Can be iterated (`for...of`, `size`) | Yes | No | | Used for temporary references | Rarely | Often | ### Automatic removal from memory ```javascript let obj = { id: 1 }; const ws = new WeakSet(); ws.add(obj); console.log(ws.has(obj)); // true obj = null; // the object is no longer reachable // the object will be removed from memory automatically by the garbage collector ``` How this works: - After `obj = null` the object is **reachable only from the `WeakSet`**, and such a reference does not count as a strong one, so the GC is free to remove it. - That is exactly what makes `WeakSet` convenient for **holding temporary or cached objects**: you never have to clean up by hand. ### A practical example: tracking processed objects ```javascript const processed = new WeakSet(); function process(obj) { if (processed.has(obj)) { console.log('Already processed'); return; } processed.add(obj); console.log('Processing:', obj.name); } const user = { name: 'Alice' }; process(user); // Processing: Alice process(user); // Already processed // after user = null the object disappears from the WeakSet automatically ``` Here the `WeakSet` acts as an "invisible flag" on the object: we do not bolt a service field such as `obj.__processed` onto it, we do not pollute the data structure, and we do not keep the object alive longer than necessary. ### In short | Property | Value | | --- | --- | | Type | A collection of unique **objects** | | Primitives | Not allowed | | Garbage collector | May remove elements | | Iteration | Impossible | | Methods | `add`, `delete`, `has` | | Common use | Caching, "processed" marks, private data | > **Summary:** `WeakSet` is a collection of unique objects that are removed from memory automatically once no other references to them remain. It is excellent for temporary marks and caching, and a poor fit when data has to be stored permanently or iterated over. ### Common mistakes - **Trying to add a primitive.** `ws.add('text')` or `ws.add(5)` is a `TypeError`, only an object can be a member. - **Looking for `size` or a loop.** Counting the elements or walking over them is impossible by design; use a regular `Set` for that. - **Storing long lived data in a `WeakSet`.** With no external references the entry may vanish at any time, this is not a storage. - **Assuming removal is instant.** The GC runs whenever it sees fit, so `has()` is not guaranteed to return `false` right after you drop the last reference. - **Confusing it with `WeakMap`.** A `WeakSet` stores the objects themselves, a `WeakMap` stores "object to value" pairs. - **Turning it into a result cache.** A `WeakSet` remembers only the fact of membership; to attach a value to an object you need a `WeakMap`.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.