It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 84 – WeakSets in JavaScript

WeakSet` is a special kind of Set that only stores objects, and those objects are held weakly—meaning they don’t prevent garbage collection if there are no other references to them.


What is a WeakSet?

  • Like a Set, a WeakSet lets you store unique values.
  • But only objects (not primitives) can be added.
  • Objects in a WeakSet are held weakly.
  • WeakSet is not iterable and has no size property.

Creating a WeakSet

const ws = new WeakSet();

const obj1 = { name: "Alice" };
const obj2 = { name: "Bob" };

ws.add(obj1);
ws.add(obj2);

console.log(ws.has(obj1)); // true

ws.delete(obj2);
console.log(ws.has(obj2)); // false

Limitations of WeakSet

  • You cannot list all elements.
  • You can't use .forEach() or get .size.
  • You can only use .add(), .has(), and .delete().
const ws = new WeakSet();
ws.add(1);  //  Error: Invalid value used in weak set

Use Case: Tracking Objects Without Preventing GC

WeakSets are good for storing metadata or tracking object states without interfering with memory cleanup.

Example:

const visitedNodes = new WeakSet();

function visit(node) {
  if (visitedNodes.has(node)) {
    console.log("Already visited");
    return;
  }

  visitedNodes.add(node);
  console.log("Visiting", node);
}

Try Your Hand

  1. Create a WeakSet and add 2 different objects.
  2. Check if a third object is in the set.
  3. Delete one and check the result.
  4. Try adding a primitive (and see the error).