Sub topic 6
Circular and Shared References
This chapter assumes you already know how to call structuredClone and which types it supports. You should also understand that object variables hold references, and that === on two objects checks whether they are the same object, not whether they have equal contents.
Real data is rarely a simple tree. A tree node may point back to its parent. Two records may point to the same settings object. A cache may store one object under several keys. A deep copy has to decide what to do with these links. structuredClone copies the reference graph itself, links included.
Two Kinds of Reference Graphs
A shared reference means two or more properties point to the same object. A circular reference means an object can reach itself by following properties, either directly (node.self = node) or through a chain (a.next = b; b.next = a).
A naive recursive copier gets both of these wrong. On a shared reference, it copies the shared object once per path that reaches it, so the copy has two separate objects where the original had one. On a circular reference, it recurses forever, or until the stack overflows.
How structuredClone Keeps the Graph Intact
During one call, the structured clone algorithm keeps an internal memory, which is a map from each original object it has visited to the copy it created for that object. Before copying an object, it checks the map:
- If the object has already been copied, it reuses that copy.
- If not, it creates a new copy, records it in the map, and then copies the object's contents.
Because the copy is recorded before its contents are filled in, a property that points back to an object still being copied finds the new copy in the map. The recursion stops there.
const node = { name: 'root' };
node.self = node;
const shared = { id: 1 };
const pair = { a: shared, b: shared };
const nodeCopy = structuredClone(node);
const pairCopy = structuredClone(pair);
console.log(nodeCopy.self === nodeCopy); // true
console.log(nodeCopy === node); // false
console.log(pairCopy.a === pairCopy.b); // true
console.log(pairCopy.a === shared); // falseThe copy has the same shape as the original. nodeCopy.self points to nodeCopy, not back to the original node. In pairCopy, a and b share one new object, so a change made through pairCopy.a shows up through pairCopy.b, exactly as it does in the original.
Comparing with the JSON Round-Trip
A JSON round-trip fails in both cases, in different ways:
const node = { name: 'root' };
node.self = node;
try {
JSON.stringify(node);
} catch (err) {
console.log(err instanceof TypeError); // true (circular structure)
}
const shared = { id: 1 };
const pair = { a: shared, b: shared };
const jsonCopy = JSON.parse(JSON.stringify(pair));
console.log(jsonCopy.a === jsonCopy.b); // false: the sharing is lostThe circular case throws a TypeError. The shared case looks fine at first, but the copy has quietly become a tree with two independent objects. This kind of bug shows up later, when an update through one path no longer reaches the other.
| Input shape | JSON round-trip | structuredClone |
|---|---|---|
| Shared nested object | Duplicated into separate objects | Stays shared within the copy |
| Circular reference | Throws `TypeError` | Points to the copy itself |
| Object used as a Map key and as a value | Not supported | Same copied object in both places |
Sharing Inside Maps, Sets and Arrays
The memory map covers every object reached during the call, including Map keys, Set entries and array elements:
const user = { name: 'Ada' };
const state = {
list: [user, user],
byUser: new Map([[user, 'admin']])
};
const copy = structuredClone(state);
const copiedUser = copy.list[0];
console.log(copy.list[1] === copiedUser); // true
console.log(copy.byUser.get(copiedUser)); // 'admin'
console.log(copy.byUser.get(user)); // undefinedThe Map lookup works with the copied user because the key and the array elements all became the same new object. Looking up the original user fails, because the original is not part of the copy.
const shared = { id: 1 };
const first = structuredClone({ ref: shared });
const second = structuredClone({ ref: shared });
console.log(first.ref === second.ref); // false
const both = structuredClone({ first: { ref: shared }, second: { ref: shared } });
console.log(both.first.ref === both.second.ref); // trueExercise
Given const a = { name: 'a' }; const b = { name: 'b', peer: a }; a.peer = b; const c = structuredClone(a); what do c.peer.peer === c and c.peer === b evaluate to, and why?
Show answer
c.peer.peer === c is true, because the algorithm records the copy of a before copying its properties, so when it reaches b.peer it reuses that copy. c.peer === b is false, because b was copied into a new object and the copy never points back to the original graph.
Exercise
You call structuredClone(order) and then, separately, structuredClone(customer). Both originals point to the same address object. Will the two copies share one address object? How would you make them share it?
Show answer
No. Each call has its own memory map, so each copy gets its own address object. To keep the sharing, clone them together in one call, for example const { order: o, customer: c } = structuredClone({ order, customer }).