What is the WeakSet object in JavaScript?

Overview

In JavaScript, we use a WeakSet object to store a collection of objects. It has the following characteristics:

  1. It can only contain objects as a value.
  2. Objects stored are unique. The same object cannot be repeated. If so, the duplicated object will be ignored.
  3. Objects are "weakly stored." If there are no other references besides WeakSet, the object will be removed from memory. This is known as garbage collection.

Syntax

const weakSet = new WeakSet([iterable])

Methods

We use three types of methods in the WeakSet object.

  • add(): We use this to add objects to the WeakSet object.
  • has(): We use this to return a boolean, verifying whether or not a value is present in the WeakSet object.
  • delete(): We use this to delete a value from the weakSet object.

Example

let obj = new WeakSet();
console.log(obj);
let objOne = {greeting: "Hi"};
obj.add(objOne)
console.log(`weakSet has objOne:`+ obj.has(objOne))
obj.delete(objOne)
console.log(`weakSet has objOne:`+ obj.has(objOne))

Explanation

  • Line 1–2: We'll create an empty weakSet() object.
  • Line 4-5: We'll use the add method to attach the object to the weakSet.
  • Line 7: We use the has method to verify if the object is present in the weakSet.
  • Line 9–10: We'll use the delete method to remove the object from the weakSet.

Free Resources