JavaScript Set and WeakSet


In JavaScript, both Set and WeakSet are objects used to store unique values. While they share some similarities, they also have key differences that make them useful in different scenarios.


1. What is a JavaScript Set?

A Set is a collection of unique values. It allows you to store values of any type, including objects, and automatically removes duplicates. Sets are useful when you need to ensure that no duplicate values are present in a collection.

Syntax to Create a Set

You can create a Set using the new Set() constructor:

const mySet = new Set();

You can also initialize a Set with values when creating it:

const numbers = new Set([1, 2, 3, 4, 5]);

In this example, the Set contains five unique values.


2. Key Features of JavaScript Set

Here are the key features of the Set object:

  • Unique Values: A Set only stores unique values. If you try to add a duplicate value, it will be ignored.
  • Any Data Type: A Set can store values of any data type: numbers, strings, objects, etc.
  • Ordered Collection: Sets remember the insertion order of the values, meaning you can iterate over them in the order they were added.
  • No Indexing: Unlike arrays, Sets do not have numeric indexes. You can only iterate through them using iteration methods.

3. Basic Operations with Sets

3.1 Adding Items to a Set

You can add values to a Set using the add() method.

const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
console.log(mySet);  // Output: Set { 1, 2, 3 }

If you try to add a duplicate value, it won’t be added:

mySet.add(3);  // No effect
console.log(mySet);  // Output: Set { 1, 2, 3 }

3.2 Checking if a Value Exists

You can check if a Set contains a value using the has() method.

console.log(mySet.has(2));  // Output: true
console.log(mySet.has(4));  // Output: false

3.3 Removing Items from a Set

To remove a specific value from a Set, use the delete() method.

mySet.delete(2);
console.log(mySet);  // Output: Set { 1, 3 }

3.4 Clearing a Set

To remove all values from a Set, use the clear() method.

mySet.clear();
console.log(mySet);  // Output: Set {}

4. Iterating Over a Set

You can iterate over the values of a Set using different methods:

4.1 Using forEach()

mySet.forEach(value => {
  console.log(value);
});

4.2 Using for...of Loop

for (let value of mySet) {
  console.log(value);
}

4.3 Using values() Method

const setValues = mySet.values();
console.log([...setValues]);  // Output: [1, 3]

5. What is a JavaScript WeakSet?

A WeakSet is similar to a Set, but with a few important differences. A WeakSet only stores objects as its values, and the values are weakly referenced. This means that if there are no other references to an object in a WeakSet, it can be garbage collected, making WeakSet more memory efficient for certain use cases.

Syntax to Create a WeakSet

You can create a WeakSet using the new WeakSet() constructor:

const myWeakSet = new WeakSet();

You can also initialize a WeakSet with an array of objects:

const obj1 = { name: 'Alice' };
const obj2 = { name: 'Bob' };
const myWeakSet = new WeakSet([obj1, obj2]);

6. Key Features of JavaScript WeakSet

  • Only Objects: A WeakSet only stores objects. Primitives (like numbers, strings, and booleans) cannot be stored in a WeakSet.
  • Weak References: The objects stored in a WeakSet are weakly referenced, meaning they are garbage-collected if there are no other references to them.
  • No Iteration: You cannot iterate over the contents of a WeakSet. This is because the contents may be garbage-collected, so the set does not expose any methods for iteration.
  • No clear() Method: A WeakSet does not have a clear() method because its items are automatically garbage collected when there are no references to them.

7. Basic Operations with WeakSets

7.1 Adding Objects to a WeakSet

You can add objects to a WeakSet using the add() method:

const myWeakSet = new WeakSet();
const obj1 = { name: 'John' };
const obj2 = { name: 'Jane' };
myWeakSet.add(obj1);
myWeakSet.add(obj2);

7.2 Checking if an Object Exists

To check if an object exists in a WeakSet, use the has() method:

console.log(myWeakSet.has(obj1));  // Output: true
console.log(myWeakSet.has(obj2));  // Output: true

7.3 Removing Objects from a WeakSet

To remove an object from a WeakSet, use the delete() method:

myWeakSet.delete(obj1);
console.log(myWeakSet.has(obj1));  // Output: false

8. Key Differences Between Set and WeakSet

Feature Set WeakSet
Key Type Any type (primitives, objects, functions) Only objects
Garbage Collection Does not support garbage collection Weak references; objects are garbage-collected if no other references exist
Iteration Supports iteration (forEach, for...of) No iteration available
Methods clear(), size, add(), has(), delete() add(), has(), delete()
Use Case Storing any unique values, with iteration Memory-efficient storage for objects that might be garbage collected

9. Use Cases for JavaScript Set and WeakSet

Use Cases for Set:

  • Unique Collection: If you need to store unique values and allow iteration over them, such as in the case of tracking unique items in a collection.
  • Set Operations: Performing mathematical set operations like union, intersection, and difference between two sets.

Use Cases for WeakSet:

  • Memory Management: If you need to store a collection of objects without preventing them from being garbage-collected when they are no longer in use, WeakSet is ideal.
  • Tracking Object States: You can use a WeakSet to track objects (e.g., elements in the DOM or certain objects in an application) that should be automatically garbage-collected when they are no longer referenced elsewhere.