The JavaScript WeakSet object
A WeakSet is like a Set but its values must be objects and are held weakly — an object in a WeakSet can still be garbage collected when nothing else references it. It has only add(), has() and delete(), no iteration and no size. Use it to tag or track objects without causing leaks.
Overview
A WeakSet is the object-only, leak-safe cousin of Set. Its values can only be objects, and it holds them weakly: membership in the WeakSet doesn't keep an object alive, so once nothing else references it, the garbage collector can remove it and its WeakSet entry disappears. A regular Set holds its values strongly, which can keep objects (and the memory they use) around longer than intended.
The API is tiny: add(obj), has(obj) and delete(obj). There's no size, no clear(), and no iteration — you can't list a WeakSet's contents, because what it still contains depends on garbage collection, which isn't observable.
Its typical use is tagging objects with a boolean fact without modifying them or risking a leak: marking which DOM nodes have been initialized, which objects have been seen during a traversal, or which instances passed a check. seen.has(node) answers "have I processed this?" and the entries clean themselves up. When you need iteration, size, or non-object values, use a regular Set instead. It mirrors WeakMap, which does the same for key-value pairs.
Syntax
const ws = new WeakSet();
const obj = {};
ws.add(obj);
ws.has(obj); // true
ws.delete(obj);
// no size, no iteration, values must be objects
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const initialized = new WeakSet();
function setup(el) {
if (initialized.has(el)) return 'already done';
initialized.add(el);
return 'initialized';
}
const node = {};
document.getElementById('out').textContent =
setup(node) + '\n' + setup(node); // initialized / already done
</script>
Best practices
- Use a
WeakSetto tag/track objects without preventing their garbage collection. - Values must be objects — use a regular Set for primitives.
- Don't expect iteration or
size; they don't exist on a WeakSet. - Reach for it to avoid leaks when marking DOM nodes or instances as "seen"/"initialized".
Frequently asked questions
What is the difference between a Set and a WeakSet?
size; a WeakSet holds only objects, weakly (so they can be garbage collected), and is not iterable.Why use a WeakSet?
Can I loop over a WeakSet?
size because its contents depend on garbage collection. Use a Set if you need to iterate.