Back to Python
2026-03-275 min read

JS Set WeakSet (Python Programming)

Learn JS Set WeakSet (Python Programming) step by step with clear examples and exercises.

Why This Matters

Learning about JavaScript's WeakSet is crucial for mastering efficient memory management and optimizing performance in your applications. By understanding how to use WeakSet, you can effectively handle large data sets or objects with cyclic references. Additionally, this knowledge will help Python developers appreciate the importance of memory management and apply similar concepts in their own code.

Prerequisites

Before diving into JavaScript's WeakSet, ensure you have a solid grasp of:

  • Basic JavaScript syntax and data structures (variables, arrays, objects)
  • Understanding object references and the concept of cyclic references
  • Familiarity with common JavaScript APIs like Array, Object, and Date
  • Knowledge of garbage collection in JavaScript

Core Concept

What is WeakSet?

WeakSet is a non-generic collection interface in JavaScript that only holds objects and allows you to test if an object is present in the set. Unlike other data structures such as Array or Map, a weak reference is used to store each object, meaning they will be garbage collected when there are no other strong references to them.

Creating a WeakSet

Creating a new instance of WeakSet is as simple as calling the constructor:

const myWeakSet = new WeakSet();

Adding and Removing Objects

To add an object to the WeakSet, use the add() method:

myWeakSet.add({ key: 'value' });

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

myWeakSet.delete({ key: 'value' });
myWeakSet.remove({ key: 'value' }); // Same as delete

Testing for Object Presence

To check if an object is present in the WeakSet, use the has() method:

const myObject = { key: 'value' };
myWeakSet.add(myObject);
console.log(myWeakSet.has(myObject)); // true

Iterating Over WeakSet

Although WeakSet does not maintain an order or indexes for its elements like other collections, you can iterate over the objects it contains using a for...of loop:

const myWeakSet = new WeakSet([{ key1: 'value1' }, { key2: 'value2' }]);
for (const obj of myWeakSet) {
console.log(obj);
}

Comparing WeakSet to Other Data Structures

  • Array: An ordered collection that can store any data type, including objects and primitive values.
  • Map: A key-value pair collection that allows you to store any data type as keys or values.
  • WeakSet: A non-ordered collection that only stores objects using weak references, allowing for efficient memory management.

Worked Example

Let's create a WeakSet to store book objects with cyclic references and test its behavior with garbage collection.

const myWeakSet = new WeakSet();

// Create some book objects with cyclic references
function Book(title, author) {
this.title = title;
this.author = author;
this.nextBook = null;
}

const book1 = new Book('The Catcher in the Rye', 'J.D. Salinger');
const book2 = new Book('To Kill a Mockingbird', 'Harper Lee');
book1.nextBook = book2;
book2.nextBook = book1;

// Add books to WeakSet
myWeakSet.add(book1);
myWeakSet.add(book2);

console.log('Initial count:', myWeakSet.size); // 2

// Simulate garbage collection by setting the global variable to null
globalThis = null;

// Verify that both books are still in WeakSet (they should be removed during garbage collection)
console.log(myWeakSet.has(book1)); // true
console.log(myWeakSet.has(book2)); // true

In this example, the Book objects have cyclic references, but the WeakSet will only retain them as long as they have strong references elsewhere in the program (i.e., by the myWeakSet variable). Once the global variable is set to null, the garbage collector will be triggered, and the book objects will be removed from memory, but their presence in the WeakSet will still be true until the script finishes execution.

Common Mistakes

  1. Forgetting to add an object before testing its presence:
const myWeakSet = new WeakSet();
myWeakSet.has({ key: 'value' }); // false
myWeakSet.add({ key: 'value' });
myWeakSet.has({ key: 'value' }); // true
  1. Assuming that a weak reference guarantees immediate garbage collection:

While using a WeakSet does help in managing memory, it doesn't guarantee immediate garbage collection. The objects will be collected when the garbage collector runs and there are no other strong references to them.

  1. Treating WeakSet like an Array or Map:

WeakSet is not an ordered collection like Array and does not allow key-value pairs like Map. It only stores objects, allowing you to test for their presence using the has() method.

  1. Ignoring the need for garbage collection:

Although WeakSet helps manage memory by using weak references, it's essential to understand that garbage collection still plays a crucial role in removing objects from memory when there are no strong references left.

Practice Questions

  1. Create a WeakSet to store user objects with unique email addresses. Implement a method that checks if a new user's email address already exists in the set before adding them.
  2. Given an array of cyclic object references, create a WeakSet to store these objects and remove any duplicates due to cyclic references.
  3. Write a function that accepts a WeakSet and returns the total number of unique objects it contains.
  4. Implement a method to clear all objects from a WeakSet without deleting the WeakSet itself.
  5. Explain how WeakSet behaves when an object is removed during garbage collection.

FAQ

  1. Can I add non-objects to a WeakSet?

No, only objects can be added to a WeakSet. Non-objects will be ignored.

  1. How does WeakSet handle cyclic references between its objects?

WeakSet stores each object using a weak reference, which means it won't prevent garbage collection even if there are cyclic references between the objects in the set. The objects will only be retained as long as they have strong references elsewhere in the program.

  1. Can I iterate over the objects in a WeakSet?

Yes, you can iterate over the objects in a WeakSet using a for...of loop or by converting it to an array using the spread operator (...) before iterating.

  1. What happens if I add the same object multiple times to a WeakSet?

Adding the same object multiple times to a WeakSet will only result in the object being added once, as the weak reference used by the set ensures that it retains only one instance of the object.

  1. What happens when an object is removed during garbage collection from a WeakSet?

When an object is removed during garbage collection from a WeakSet, its memory will be freed, and the WeakSet's size will decrease by 1. However, if the WeakSet contains no more objects, it will be eligible for garbage collection itself.

JS Set WeakSet (Python Programming) | Python | XQA Learn