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.
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}));
{"original":{"title":"Draft","style":{"ink":"purple"}},"copy":{"title":"Copy","style":{"ink":"purple"}},"sameStyle":true}| Field or reference | Original after edit | Copy after edit |
|---|---|---|
| title | Draft | Copy |
| style.ink | purple | purple |
| style identity | Shared with copy | sameStyle: 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.
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}));
{"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.
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}));
{"sourceHasExtra":false,"copyHasExtra":true,"sameStyle":true}