Skip to content

WeakSet

In one line

A WeakSet is a collection of unique objects held weakly, so entries can be garbage collected.

In simple words

A WeakSet is like a Set, but it only holds objects (or symbols) and holds them weakly. If nothing else references an object in the set, it can be garbage collected and disappears from the set. This is useful for tagging objects without preventing their collection.

Like WeakMap, WeakSet is not enumerable — no size, no iteration. You can only add, has, and delete. The weak holding means you never leak an object just by putting it in the set.

Use WeakSet to mark objects as "processed", "visited", or "special" without keeping them alive. For example, track which DOM nodes you have already decorated, or which objects have been validated, and the tracking disappears when the objects do.

Example

javascript
const processed = new WeakSet();

function process(obj) {
  if (processed.has(obj)) return; // skip already-processed
  // ... do work ...
  processed.add(obj);
}

const node = document.createElement("div");
process(node);
process(node); // skipped — already in the WeakSet
// When `node` is GC'd, the WeakSet entry vanishes

The WeakSet tracks processed objects. Re-processing is skipped. When the object is collected, the entry is freed.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary