Question 55
Question
Answer
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
const node1 = new Node('A');
const node2 = new Node('B');
// Potential for a circular reference here:
node1.next = node2; // Assuming we were building a linked list
node2.next = node1; // The problem!
// Using WeakRef to break the cycle
const weakRefToNode1 = new WeakRef(node1);
// node1 is still reachable through this reference
console.log(weakRefToNode1.deref()); // Output: { data: 'A', next: null }
// If node2 is no longer referenced elsewhere...
delete node2;
// ...and node1 doesn't have any other references, it'll be garbage collected!
Last updated