Javascript - Collection WeakSet


WeakSet object stores weakly held objects in a collection.

WeakSet doesn't prevent its elements from being garbage collected.

Values in a WeakMap must be unique object references.

A WeakSet is not iterable and does not have a size property.

A WeakSet supports only three methods:

  • add(value)
  • has(value)
  • delete(value)


let ws = new WeakSet(); 
const obj = {}; 
const foo = {}; 


ws.has(window); // true 
ws.has(foo);    // false, foo has not been added to the set 

ws.delete(window); // removes window from the set 
ws.has(window);    // false, window has been removed 

Use a WeakSet over a Set when you need Garbage Collection capabilities in the collection.

The following code shows how to prevent the usage of class methods on any object that was not created by the class constructor.

const fruits = new WeakSet(); 

class Fruit { 
  constructor() { 

  getName() { 
    if (!fruits.has(this)) { 
      throw new TypeError("getName() called on an incompatible object!"); 
    } else { 
        // returns the name