Learn JavaScript
❯ collections.copying

Shallow vs Deep Copy in JavaScript

$concept

Assignment copies references, spread/Object.assign copy one level (nested objects stay shared), and true independence needs deep copying — JSON round-trips (losing functions/undefined/dates/circularity), structuredClone() (handling Maps, Sets, Dates, circular graphs natively), or manual recursion.

Rule: spread for flat updates, structuredClone for faithful duplicates, custom cloners for class instances (prototypes don't survive either method). React-style immutable updates ({...state, nested: {...state.nested, x: 1}}) compose shallow copies deliberately level by level.

$how it works
1

Assignment aliases

const b = a shares everything — mutations through either name affect the one object.

2

Spread copies shallowly

{...a} duplicates top-level fields; nested objects remain shared references.

3

structuredClone deep-copies

Handles nesting, Maps, Dates, circular refs — the standard faithful duplicate (functions still excluded).

4

Update immutably by levels

{...s, nested: {...s.nested, x: 1}} — fresh objects along the changed path, shared references elsewhere.

$example
let a = { x: 1, deep: { y: 2 } };
let shallow = { ...a };
shallow.deep.y = 99;
console.log(a.deep.y);
let deep = structuredClone(a);
deep.deep.y = 7;
console.log(a.deep.y, deep.deep.y);
Output
99
99 7
1Spread shares the nested object — mutating through shallow corrupts the original to 99.
2structuredClone duplicates fully — changing the clone leaves the original at 99.
3Shallow sharing versus deep independence, demonstrated destructively.
$use cases
Immutable state updates in React/Redux reducers
Deep duplicates via structuredClone for snapshots and history
Level-by-level spreads for surgical nested updates
Custom cloners preserving class prototypes

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.