Sub topic 6
Circular and Shared References
This chapter assumes you know JavaScript objects and arrays, the === operator, basic Map and Set use, and try/catch. It also assumes you have read the earlier chapters on shallow copies, the JSON round-trip, and the basics of structuredClone.
So far, deep copying has looked like a tree walk. You start at the top object, copy each property, and repeat for every nested object. Real data is often not a tree, though. A parent may point to its child while the child points back to the parent. Two records may hold the same settings object. A cache may keep its own key objects inside a Map. This kind of data forms a graph. A graph-shaped value is where simple copying methods break and where structuredClone behaves differently from them.
Trees, Graphs and Identity
A reference graph is the set of objects in a value plus the arrows between them, where each property that holds an object counts as an arrow. Two kinds of structure matter here:
- A shared reference exists when two or more places point to the same object. For example,
pair.aandpair.bboth hold onesharedobject. - A circular reference exists when following the arrows brings you back to an object you already visited. For example,
node.self === node.
In both cases the important fact is identity: whether two references point to the very same object, which is what === tests for objects. A correct deep copy of a graph has to make new objects and also reproduce the identity relationships between them. If a === b in the original, then copy.a === copy.b should hold in the copy, and neither should equal the original object.
What structuredClone Does
Here is the behavior in one example:
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 circular reference comes back as a cycle inside the copy: nodeCopy.self points to nodeCopy, not to the original node. The shared object is copied once, and both properties of the copy point to that single new object. Nothing in the copy points back into the original.
How It Works Internally: The Memory Map
The structured clone algorithm in the HTML specification keeps a memory map while it serializes a value. The map records every object it has already processed, keyed by the original object. Each time it reaches an object, it does this:
- Look the object up in the memory map.
- If it is there, write a back-reference to the earlier entry instead of serializing it again.
- If it is not there, add it to the map first, then serialize its contents.
During deserialization the back-references resolve to the objects already rebuilt. That is how cycles and shared objects end up as cycles and shared objects in the copy.
The order in step 3 matters. The object goes into the map before its children are visited. If a child points back to the parent, the lookup finds the parent and stops. Without that ordering, the walk would recurse forever.
Building the Same Idea Yourself
You can see why this matters by writing a deep copy for plain objects and arrays by hand. The naive recursive version has no memory, so a cycle sends it into endless recursion:
function naiveClone(value) {
if (typeof value !== 'object' || value === null) return value;
const copy = Array.isArray(value) ? [] : {};
for (const key of Object.keys(value)) {
copy[key] = naiveClone(value[key]);
}
return copy;
}
const node = { name: 'root' };
node.self = node;
try {
naiveClone(node);
} catch (err) {
console.log(err.constructor.name); // 'RangeError' in V8 (Node.js, Chrome)
}Firefox reports the same failure as an InternalError with the message "too much recursion". Adding a memory map fixes both cycles and sharing:
function cloneGraph(value, seen = new Map()) {
if (typeof value !== 'object' || value === null) return value;
if (seen.has(value)) return seen.get(value);
const copy = Array.isArray(value) ? [] : {};
seen.set(value, copy); // register before visiting children
for (const key of Object.keys(value)) {
copy[key] = cloneGraph(value[key], seen);
}
return copy;
}
const node = { name: 'root' };
node.self = node;
const shared = { id: 1 };
const pair = { a: shared, b: shared };
const nodeCopy = cloneGraph(node);
const pairCopy = cloneGraph(pair);
console.log(nodeCopy.self === nodeCopy); // true
console.log(pairCopy.a === pairCopy.b); // true
console.log(pairCopy.a === shared); // falseThis is a teaching sketch. It handles only plain objects and arrays. structuredClone uses the same idea across every type it supports, including Map, Set, Date and typed arrays. You rarely need to write this yourself, but knowing the mechanism helps you predict the results.
How Other Copying Methods Compare
The earlier chapters introduced spread and the JSON round-trip. Each one treats graphs differently.
| Method | Circular reference | Shared reference |
|---|---|---|
| Spread / `Object.assign` | No error. Nested cycle still points into the original | Nested objects are still the original objects |
| `JSON.parse(JSON.stringify(v))` | Throws `TypeError` | Each use is copied separately, so sharing is lost |
| Naive recursion | Endless recursion, stack overflow | Each use is copied separately, so sharing is lost |
| `structuredClone` | Rebuilt as a cycle in the copy | Preserved as one new shared object |
The JSON cases are easy to check:
const node = { name: 'root' };
node.self = node;
try {
JSON.stringify(node);
} catch (err) {
console.log(err.name); // 'TypeError'
}
const shared = { id: 1 };
const pair = { a: shared, b: shared };
const jsonCopy = JSON.parse(JSON.stringify(pair));
console.log(jsonCopy.a === jsonCopy.b); // false
jsonCopy.a.id = 2;
console.log(jsonCopy.b.id); // 1Losing sharing is a quiet kind of bug. The JSON copy looks correct when you print it. Its behavior changes only when you mutate it: an update through a no longer shows through b. If your code relies on one object being the single source of truth, such as a shared config or a normalized entity, the JSON copy breaks that without any error.
Edge Cases Worth Knowing
Object Keys Inside Maps and Sets
Map keys and Set members go through the same memory map. If an object is used both as a Map key and as a property somewhere else, the copy uses the same new object in both places:
const key = { id: 1 };
const lookup = new Map([[key, 'first']]);
const state = { current: key, lookup };
const copy = structuredClone(state);
console.log(copy.lookup.get(copy.current)); // 'first'
console.log(copy.lookup.get(key)); // undefined
console.log(copy.current === key); // falseThis is often what you want: lookups inside the copy keep working. It also means you can't use your original key objects to read from the copied Map. The copy's keys are new objects, and Map compares object keys by identity.
Containers can also contain themselves:
const set = new Set();
set.add(set);
const setCopy = structuredClone(set);
console.log(setCopy.has(setCopy)); // true
console.log(setCopy.has(set)); // falseTyped Arrays That Share a Buffer
A typed array is a view onto an ArrayBuffer. When two views share one buffer, that buffer is a shared reference, and structuredClone keeps it shared:
const buffer = new ArrayBuffer(4);
const state = {
bytes: new Uint8Array(buffer),
words: new Uint16Array(buffer)
};
const copy = structuredClone(state);
console.log(copy.bytes.buffer === copy.words.buffer); // true
console.log(copy.bytes.buffer === buffer); // false
copy.bytes[0] = 255;
console.log(copy.words[0] !== 0); // true: both views see the write
console.log(state.bytes[0]); // 0: the original is untouchedIf the copy gave each view its own buffer, code that writes through one view and reads through the other would quietly stop working.
Sharing Only Exists Within One Call
The memory map lives for a single structuredClone call. Two separate calls know nothing about each other:
const shared = { count: 0 };
const left = { ref: shared };
const right = { ref: shared };
const leftCopy = structuredClone(left);
const rightCopy = structuredClone(right);
console.log(leftCopy.ref === rightCopy.ref); // false
const [leftTogether, rightTogether] = structuredClone([left, right]);
console.log(leftTogether.ref === rightTogether.ref); // trueIf several values must keep their shared parts after copying, clone them together in one container and destructure the result. This mistake often shows up when code copies the items of a list one at a time with items.map(item => structuredClone(item)). Calling structuredClone(items) once keeps sharing between the items.
Cost and Depth
The memory map grows with the number of objects in the value, so cloning a large graph costs both time and memory in proportion to its size. Sharing doesn't make the copy cheaper to build: each object is still visited once. It does keep the copy from blowing up in size, because a shared object is copied once instead of once per reference. Very deep nesting, such as a linked list with hundreds of thousands of nodes, can still exhaust the call stack in some engines. If you work with structures like that, test with realistic sizes.
Identity Is Rebuilt, Not Kept
No object in the copy is === to any object in the original. This is the point of a deep copy, but it affects code that stores identities elsewhere. A WeakMap that uses original objects as keys won't recognize the copies. An includes check against an array of original objects will fail. Any outside bookkeeping keyed by object identity has to be rebuilt for the copy.
Summary of the Rules
structuredClonecopies each distinct object exactly once per call.- Every reference to an already-copied object becomes a reference to its copy, so cycles stay cycles and shared objects stay shared.
- Nothing in the copy points into the original, and nothing in the copy is
===to an original object. - This applies across properties, array slots,
Mapkeys and values,Setmembers and the buffers behind typed arrays. - Separate calls don't share a memory map, so clone related values together.
Exercise
Given const tag = { label: 'x' }; const doc = { tags: [tag, tag], primary: tag };, what do c.tags[0] === c.primary and c.tags[0] === tag print after const c = structuredClone(doc)? What would the first comparison print for a JSON round-trip copy?
Show answer
c.tags[0] === c.primary is true, because all three references to tag resolve to one new object in the copy. c.tags[0] === tag is false, because the copy never reuses original objects. With JSON.parse(JSON.stringify(doc)), the first comparison is false: JSON writes tag out three times, and parsing creates three separate objects.
Exercise
A tree has child.parent = root and root.children = [child]. Explain why JSON.stringify(root) fails, and why cloneGraph from this chapter succeeds only because it calls seen.set(value, copy) before looping over the keys.
Show answer
JSON serialization has no memory of visited objects, so it detects the cycle root → children → child → parent → root and throws a TypeError. cloneGraph records root and its empty copy in seen before visiting children. When the walk reaches child.parent, the lookup finds root and returns its copy instead of recursing. If the set call came after the loop, the walk would visit root again and again until the stack overflowed.
Exercise
You have const users = [alice, bob], where alice.team and bob.team refer to the same team object. A teammate writes const copies = users.map(u => structuredClone(u)); and then renames the team through copies[0].team.name = 'New'. What does copies[1].team.name show, and how do you fix it?
Show answer
It still shows the old name. Each structuredClone call has its own memory map, so the two copies got separate team objects. Use const copies = structuredClone(users); so both users are cloned in one call and copies[0].team === copies[1].team.