HomepageExploring JavaScript (ES2025 Edition)
You can support this book: buy it or donate
(Ad, please don’t block.)

39 WeakSets (WeakSet) ES6 (advanced)

39.1 How are WeakSets different from Sets?

WeakSets are similar to Sets, with the following differences:

39.2 Use case for WeakSets: marking objects

Given that we can’t iterate over the elements of WeakSets, there are not that many use cases for them.

We can use WeakSets to mark objects – for example:

const isSaved = new WeakSet();
{
  const obj = {};
  isSaved.add(obj); // (A)
  assert.equal(
    isSaved.has(obj), // (B)
    true
  );
}
// (C)

In a way, we created a boolean property for obj, but stored it externally. If isSaved were a property, the previous code would look as follows:

{
  const obj = {};
  obj.isSaved = true;
  assert.equal(
    obj.isSaved,
    true
  );
}

39.2.1 Example: Marking objects as safe to use with a method

The following code demonstrates how a class can ensure that its methods are only applied to instances that were created by it (based on code by Domenic Denicola):

const instancesOfSafeClass = new WeakSet();

class SafeClass {
  constructor() {
    instancesOfSafeClass.add(this);
  }

  method() {
    if (!instancesOfSafeClass.has(this)) {
      throw new TypeError('Incompatible object!');
    }
  }
}

const safeInstance = new SafeClass();
safeInstance.method(); // works

assert.throws(
  () => {
    const obj = {};
    SafeClass.prototype.method.call(obj); // throws an exception
  },
  TypeError
);

39.3 WeakSet API

The constructor and the three methods of WeakSet work the same as their Set equivalents: