> For the complete documentation index, see [llms.txt](https://choubey.gitbook.io/javascript-interview-questions/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://choubey.gitbook.io/javascript-interview-questions/question-53.md).

# Question 53

### Question

How would you create an interdependent object graph using `WeakMap` and `WeakSet`?

### Answer

Here's how you can build an interdependent object graph leveraging the strengths of `WeakMap` and `WeakSet`:

**Core Concepts:**

* **Object Relationships:** We'll define relationships between objects (e.g., "owns," "references") using `WeakMap` to store these connections.
* **Weak References for Safety:** Employ `WeakMap` and `WeakSet` throughout to ensure that if an object is no longer referenced elsewhere, it gets garbage collected without causing circular dependencies or memory leaks.

**Example: Representing a Simple Social Network**

```javascript
class Person {
  constructor(name) {
    this.name = name;
    this._relationships = new WeakMap(); // Store relationships (e.g., 'friendsWith')
  }

  addFriend(friend) {
    this._relationships.set('friendsWith', friend);
    friend._relationships.set('knows', this); 
  }
}

const john = new Person('John');
const jane = new Person('Jane');
john.addFriend(jane);

// Now, 'john' and 'jane' have a relationship via their _relationships WeakMaps.
```

**Explanation:**

1. **`Person` Class:** Each `Person` object has:
   * A `name`.
   * A private `_relationships` `WeakMap` to store its connections (friendships).
2. **`addFriend()` Method:**
   * Sets a 'friendsWith' relationship from one person (`this`) to the friend using `_relationships.set()`.
   * Does the same for the reverse direction ('knows') on the friend object, establishing a bidirectional connection.
3. **Weak References:** The use of `WeakMap` ensures that:
   * If a `Person` object is no longer referenced by anything else (e.g., removed from memory), its `_relationships` will automatically be cleared, breaking the connection and allowing for garbage collection.

**Additional Considerations:**

* **Traversing Relationships:** You can iterate through relationships using `for...of` loops or manually checking `_relationships` for keys like 'friendsWith'.
* **Complex Graphs:** For more intricate graphs with various relationship types, consider using a custom class to represent connections (e.g., `Relationship` with properties for type and objects).
