Skip to content
Astera Technology

Find the nested reference shared by a shallow copy

Separate copied top-level values from a nested object that remains shared.

Download complete case notes and answer keys ↓

Trace the fixed program

Copy a draft with object spread. Change the copy’s title and nested ink. Identify which changes can reach the original.

Complete original program
const original={title:'Draft',style:{ink:'green'}};
const copy={...original};copy.style.ink='purple';copy.title='Copy';
console.log(JSON.stringify({original,copy,sameStyle:original.style===copy.style}));
Exact console output
{"original":{"title":"Draft","style":{"ink":"purple"}},"copy":{"title":"Copy","style":{"ink":"purple"}},"sameStyle":true}
Values and execution
Field or referenceOriginal after editCopy after edit
titleDraftCopy
style.inkpurplepurple
style identityShared with copysameStyle: true

Explain the result

Spread copies the own enumerable property values into a new outer object. A string value is copied, but style holds an object reference, so both outer objects point to the same style. Copy the specific nested branch before changing it. This repair is not a general deep-copy algorithm.

Test the alternative

A new outer object is not enough to preserve an old nested value. Repair a fresh green source by copying style too; a different unedited metadata branch still remains shared.

Separate finite alternative
const original={title:'Draft',style:{ink:'green'},meta:{size:4}};
const copy={...original,style:{...original.style,ink:'purple'}};copy.title='Copy';
console.log(JSON.stringify({originalInk:original.style.ink,copyInk:copy.style.ink,sameStyle:original.style===copy.style,sameMeta:original.meta===copy.meta}));
Alternative output
{"originalInk":"green","copyInk":"purple","sameStyle":false,"sameMeta":true}

Work the boundary case

Where should the copy be made to change style.ink without changing the old note?

Show the worked answer

Create a new outer note and a new style object, then set ink on that branch. Other nested branches need their own decision if they will be edited.

Fresh boundary program
const original={style:{ink:'green'}};const copy={...original};copy.extra=1;
console.log(JSON.stringify({sourceHasExtra:Object.hasOwn(original,'extra'),copyHasExtra:Object.hasOwn(copy,'extra'),sameStyle:original.style===copy.style}));
Boundary output
{"sourceHasExtra":false,"copyHasExtra":true,"sameStyle":true}

Original example files

Related resources