Cover Image for JavaScript WeakSet
118 views

JavaScript WeakSet

The JavaScript WeakSet is an object that allows you to store a collection of weakly referenced objects. It is similar to a Set, but with some key differences:

  1. WeakSet only accepts objects as its elements. Primitive values like numbers or strings cannot be stored in a WeakSet.
  2. The objects stored in a WeakSet are held by weak references, which means they can be garbage collected if there are no other strong references to them. This makes WeakSet suitable for managing object relationships where the existence of the objects depends on other parts of your code.
  3. WeakSet does not have built-in methods for iterating over its elements or checking its size. You can only check if an object exists in the WeakSet or delete an object from it.

Here’s an example of how to use a WeakSet:

JavaScript
// Create a WeakSet
const weakSet = new WeakSet();

// Create some objects
const obj1 = { name: 'Object 1' };
const obj2 = { name: 'Object 2' };

// Add objects to the WeakSet
weakSet.add(obj1);
weakSet.add(obj2);

// Check if an object exists in the WeakSet
console.log(weakSet.has(obj1)); // Output: true

// Delete an object from the WeakSet
weakSet.delete(obj2);

// Check if an object still exists in the WeakSet
console.log(weakSet.has(obj2)); // Output: false

It’s important to note that WeakSet is not enumerable, which means you cannot iterate over its elements using loops or built-in methods like forEach. Also, since the objects stored in a WeakSet are weakly referenced, you need to ensure that you have other strong references to those objects if you want to keep them from being garbage collected.

WeakSet is commonly used in scenarios where you need to associate some metadata or additional information with objects without affecting their lifecycle or memory management.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS