Blog / October 7, 2023 / 4 mins read / By Suneet Agrawal

Set vs WeakSet in JavaScript

JavaScript provides various data structures to manage collections of data, and two commonly used ones are Set and WeakSet. Both are used to store collections of values, but they have distinct characteristics and use cases. In this blog, we will explore the differences between Set and WeakSet with examples to help you understand when to use each one.

Set

A Set is a built-in JavaScript data structure introduced in ECMAScript 6 (ES6) that allows you to store a collection of unique values. It can store any type of values, including primitive types and objects. Here’s an example of how to create and use a Set:

// Creating a Set
const mySet = new Set();

// Adding values to the Set
mySet.add(1);
mySet.add('Hello');
mySet.add({ name: 'John' });

// Checking the size of the Set
console.log(mySet.size); // Output: 3

// Checking if a value exists in the Set
console.log(mySet.has('Hello')); // Output: true

// Deleting a value from the Set
mySet.delete('Hello');

// Iterating through the Set
for (const item of mySet) {
  console.log(item);
}

WeakSet

A WeakSet is also a collection of values, but it has a different purpose and behavior compared to Set. The primary difference is that a WeakSet can only store objects and does not prevent those objects from being garbage collected when they are no longer in use. This means that a WeakSet does not hold strong references to its elements, making it suitable for scenarios where you want to store objects but don’t want to prevent them from being automatically cleaned up by the garbage collector. Here’s an example:

// Creating a WeakSet
const myWeakSet = new WeakSet();

// Adding objects to the WeakSet
const obj1 = { name: 'Alice' };
const obj2 = { name: 'Bob' };
myWeakSet.add(obj1);
myWeakSet.add(obj2);

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

// Deleting an object from the WeakSet
myWeakSet.delete(obj1);

// The WeakSet automatically removes references to deleted objects
console.log(myWeakSet.has(obj1)); // Output: false

Differences Between Set and WeakSet

Now that we’ve discussed Set and WeakSet individually, let’s highlight the key differences between them:

  1. Allowed Values:
  • Set: Set can store any type of values, including primitive types (numbers, strings, booleans) and objects. It ensures that only unique values are stored.
  • WeakSet: WeakSet can only store objects. Attempting to add non-object values like numbers or strings will result in an error. This restriction is because WeakSet is designed to work with object references.
  1. Garbage Collection:
  • Set: Objects stored in a Set are held by strong references, meaning they won’t be garbage collected as long as the Set retains a reference to them. This can lead to memory leaks if you unintentionally retain objects.
  • WeakSet: Objects stored in a WeakSet are held by weak references, allowing them to be garbage collected as soon as no other strong references to those objects exist. This behavior is useful for scenarios where you want to avoid memory leaks and allow automatic cleanup of objects.
  1. Iteration Order:
  • Set: Set maintains the insertion order of values. When you iterate over a Set, values are returned in the order they were added.
  • WeakSet: WeakSet does not provide a way to iterate over its elements. This is because it doesn’t guarantee any specific order, and it’s primarily used for managing object relationships rather than value retrieval.
  1. Size Property:
  • Set: Set has a size property that allows you to determine the number of elements it contains.
  • WeakSet: WeakSet does not have a size property, so you cannot directly obtain the number of elements it contains. You typically use WeakSet for membership checks and object management rather than counting its elements.
  1. Use Cases:
  • Set: Use Set when you need to manage collections of unique values and order matters, or when you want to use non-primitive values as keys.
  • WeakSet: Use WeakSet when you want to store objects but do not want to prevent them from being garbage collected, or when you need to create relationships between objects without strong references.

Use Cases

Now that we’ve seen the basic differences between Set and WeakSet, let’s discuss when to use each one.

Use Set When:
  • You need to store a collection of unique values, and the order of insertion matters.
  • You want to use non-primitive values (objects, arrays) as keys.
  • You want to maintain strong references to the values in the collection.
Use WeakSet When:
  • You want to store a collection of objects and don’t want to prevent them from being garbage collected.
  • You need to associate metadata or additional information with objects.
  • You want to create relationships between objects without preventing them from being released when they are no longer needed.

Conclusion

In summary, Set and WeakSet are both useful data structures in JavaScript, but they serve different purposes. Set is ideal for managing collections of unique values, while WeakSet is designed for managing objects and allows them to be garbage collected when they are no longer referenced. Choosing the right data structure depends on your specific use case and requirements. Understanding these differences will help you make informed decisions when working with collections in JavaScript.

Comments