Learnitweb

WeakSet in JavaScript

1. Introduction

A WeakSet is a collection of unique objects and references to objects in a WeakSet are held weakly. The term weakly here means that if no other references to an object stored in WeakSet exist, those objects can be garbage collected.

  • WeakSet can contain only objects.
  • Since objects of WeakSet are held weakly and can be garbage collected even if the WeakSet exists, WeakSet is not enumberable.

2. Use case of WeakSet

When you want to keep a track of large number of objects references, you can use WeakSet. For example, you can use WeakSet to track users which visited the website.

3. Constructor

WeakSet()

This creates a new WeakSet object.

Example

const weakSet = new WeakSet();

4. Add element to WeakSet

add(value): Appends value to the WeakSet object.

// create a WeakSet
const weakSet = new WeakSet();

const user1 = { userId: 1 };
const user2 = { userId: 2 };

// add values to WeakSet
weakSet.add(user1);
weakSet.add(user2);

5. Delete value from WeakSet

delete(value): This method removes value from the WeakSet.

const weakSet = new WeakSet();
const user1 = { userId: 1 };
const user2 = { userId: 2 };

// add values to WeakSet
weakSet.add(user1);
weakSet.add(user2);

//delete value from WeakSet
weakSet.delete(user1);

6. Check a value in WeakSet

has(value): This method returns true if the value is present in the WeakSet else returns false.

const weakSet = new WeakSet();
const user1 = { userId: 1 };
const user2 = { userId: 2 };

// add value to WeakSet
weakSet.add(user1);
weakSet.add(user2);

//check if value exists
weakSet.has(user1);  // true