Circular References in Modern Engines
You'll learn: Why circular references don't cause leaks by themselves in modern JavaScript, but can still leak when combined with closures or external references.
The Old Fear vs. Modern Reality
In older JavaScript environments, circular references—where object A references object B, and B references A—were notorious for causing memory leaks. Developers learned to fear them.
Good news: Modern garbage collectors use mark-and-sweep algorithms that handle circular references automatically. If two objects only reference each other but nothing from outside can reach them, both get collected.
The Remaining Danger
However, circular references can still cause leaks when combined with other patterns:
Closures holding circular structures:
function createLeak() {
let obj1 = {};
let obj2 = { ref: obj1 };
obj1.ref = obj2; // Circular!
// This closure keeps the entire circular structure alive
return function() {
console.log(obj1);
};
}
// The returned function keeps obj1 (and obj2) reachable forever
const leak = createLeak();
External references:
const registry = [];
function addNode() {
let parent = { children: [] };
let child = { parent: parent }; // Circular
parent.children.push(child);
registry.push(parent); // External reference keeps it all alive
}
The circular reference itself isn't the problem—it's that something else maintains reachability to the structure.
Key Takeaway: Modern GC handles isolated circular references perfectly, but they leak when captured by closures you keep around or stored in long-lived collections. The leak comes from the external anchor, not the cycle itself.