Shallow vs Deep Copy in JavaScript
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.
Assignment aliases
const b = a shares everything — mutations through either name affect the one object.
Spread copies shallowly
{...a} duplicates top-level fields; nested objects remain shared references.
structuredClone deep-copies
Handles nesting, Maps, Dates, circular refs — the standard faithful duplicate (functions still excluded).
Update immutably by levels
{...s, nested: {...s.nested, x: 1}} — fresh objects along the changed path, shared references elsewhere.
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);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.