Skip to main content
CodeOath
← All posts

JavaScript60 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Part 14 of 16 · ~1 min

Shallow Copy vs. Deep Copy

By this point you've already brushed up against this idea three separate times — .slice(), spread, Object.assign() — without it ever being spelled out directly, so here's the actual definition. A shallow copy gives you a brand-new outer container, but whatever was sitting inside the old one — another object, another array — is the identical item, not a duplicate, just now reachable from two places at once. A deep copy rebuilds every layer instead, so nothing about the new structure still points back at the old one, no matter how far down you go.

const original = candidates[0]; // Priya — has a nested `tags` array

const shallow = { ...original };
shallow.tags.push("kubernetes");
console.log(original.tags); // ["node", "postgres", "kubernetes"] — leaked through the shared array

const deep = structuredClone(original);
deep.tags.push("go");
console.log(original.tags); // still ["node", "postgres", "kubernetes"] — completely unaffected this time

Worth remembering because nothing else in this whole reference goes deeper than shallow by default — not spread, not .slice(), not Object.assign(), not the fresh objects .map() hands you back. structuredClone(), or a real deep-clone utility from a library, is what you reach for specifically once a record's nested structure needs to be genuinely independent, not just superficially separate. Most of the time — flat records, nothing meaningfully nested — a shallow copy already gets the job done for less, so there's rarely a reason to default to the heavier option.