Home

WeakSet

WeakSet is a built-in collection in JavaScript that stores object references with weak memory semantics. It is designed to track object presence without preventing garbage collection. Only objects can be added to a WeakSet; attempting to add a non-object value results in a TypeError. The set itself does not expose its elements, and elements are not enumerable.

The core operations of a WeakSet are add, has, and delete. However, it has important limitations: there

In practice, WeakSet is often used to track metadata or associations for objects without preventing their disposal.

Relation to other structures: a WeakSet stores only object references and does not offer iteration, unlike

is
no
size
property,
no
clear
method,
and
the
contents
cannot
be
iterated
or
directly
inspected.
Because
the
references
are
weak,
the
JavaScript
engine
may
garbage
collect
an
object
that
is
only
contained
in
the
WeakSet,
and
such
objects
disappear
from
the
set
without
any
observable
notification.
This
behavior
means
WeakSet
is
not
suitable
for
scenarios
that
require
enumeration
or
lifetime
guarantees.
A
common
use
case
is
marking
DOM
nodes
or
other
objects
to
indicate
a
special
status
or
to
prevent
repeated
processing,
while
allowing
the
objects
themselves
to
be
garbage
collected
when
no
longer
referenced
elsewhere.
Set
which
stores
values
with
strong
references
and
supports
iteration.
It
is
also
distinct
from
WeakMap,
which
stores
key-value
pairs
with
weak
keys.
WeakSet
emphasizes
membership
information
about
objects
without
owning
them,
enabling
memory-efficient
patterns
in
certain
caching
or
cleanup
tasks.