WeakSet
A collection of objects held weakly, with no duplicates.
Syntax
const ws = new WeakSet()
Examples
const ws = new WeakSet();
const obj = {};
ws.add(obj);
console.log(ws.has(obj));
ws.delete(obj);
console.log(ws.has(obj));
Output
true
false
const seen = new WeakSet();
function visit(node) {
if (seen.has(node)) return "already";
seen.add(node);
return "first";
}
const n = {};
console.log(visit(n), visit(n));
Output
first already
Notes
- Only objects (or non-registered symbols) can be stored, held weakly.
- Not iterable and has no `size`; only `add`, `has`, `delete`.
- Handy for tagging objects (e.g. cycle detection) without retaining
them.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 36 |
| firefox | 34 |
| safari | 9 |
| edge | 12 |
| node | 0.12 |