Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

WeakSet: checking, adding, and deleting members

Use `has()` to check membership, `add()` to insert a value, and `delete()` to remove it. The three methods differ in what they return and how they handle invalid values.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

weakSet.has(value)    // boolean
weakSet.add(value)    // the same WeakSet instance
weakSet.delete(value) // boolean

WeakSet.prototype.has/add/delete is shorthand for three methods on WeakSet.prototype, not the name of a single method. Call them on an instance, as in seen.has(value). Calling one without a WeakSet instance as this throws a TypeError, including when you detach it and call it as a plain function.

has(value) returns true if the value is present and false otherwise; it does not change the set. add(value) inserts the value only if it is absent and, on success, returns the same instance, so you can chain calls. delete(value) returns true only if it removed a member; otherwise it returns false. Membership is based on identity, not contents: two separately created { id: 1 } objects are distinct members.

ECMAScript 2024 allows objects (including functions) and non-registered symbols, such as Symbol(). Symbols from the global registry, returned by Symbol.for(), and other primitives, such as 1 and null, are not allowed. For an invalid value, add() throws a TypeError, while has() and delete() return false. Older runtimes may accept only objects; check symbol support in your target runtime.

An entry in a WeakSet does not by itself keep a value alive. If the value is no longer strongly reachable, it may be garbage-collected; do not rely on when that happens. A WeakSet is not iterable and has no size property. Use it to mark objects you have already processed; if you need to iterate or count members, use Set, which holds its members strongly.

Examples

{
  const seen = new WeakSet();
  const task = { id: 1 };
  const lookalike = { id: 1 };

  console.log(seen.add(task).add(task) === seen);
  console.log(seen.has(task));
  console.log(seen.has(lookalike));
  console.log(seen.delete(task));
  console.log(seen.delete(task));
  console.log(seen.has(task));
  console.log(seen.has(1));
  console.log(seen.delete(1));

  try {
    seen.add(1);
  } catch (error) {
    console.log(error instanceof TypeError);
  }
}

Result

true
true
false
true
false
false
false
false
true

Adding `task` twice still returns `seen`. `lookalike` has the same contents but is not a member. Only the first deletion of `task` returns `true`. The final `true` confirms the error type for `add(1)`; the output does not depend on garbage collection.

Related lessons

  • JavaScript · Lesson 30 · Intermediate · Version: 3

Sources