Skip to main content

Shallow vs deep object copying

In short

Copy typeWhat it doesNested objects
Shallow copyCopies only the top level of propertiesReferences to the original objects are kept
Deep copyCopies the entire tree (including nested objects)Creates new copies of all nested structures

Shallow copy example

javascript
const user = { name: 'Tim', address: { city: 'Kyiv' } }; const clone = { ...user }; // shallow copy clone.address.city = 'Lviv'; console.log(user.address.city); // "Lviv"

Why this happened:

  • { ...user } copies only the first level of properties;
  • address is an object, and the copy keeps the same reference to it;
  • changing clone.address.city affected the original.

Deep copy example

javascript
const user = { name: 'Tim', address: { city: 'Kyiv' } }; const clone = structuredClone(user); // deep copy clone.address.city = 'Lviv'; console.log(user.address.city); // "Kyiv"

Here a fully independent copy is created: all nested objects are copied anew too.


Illustration (a simple analogy)

Imagine:

javascript
user ──► address ──► { city: 'Kyiv' } clone ─┘ ↑ └── (the same reference)

In a shallow copy, both variables "point" to the same inner object.

With a deep copy:

javascript
user ──► address1 ─► { city: 'Kyiv' } clone ─► address2 ─► { city: 'Lviv' }

These are two fully independent objects.


How to make a deep copy

MethodDeep copyNotes
structuredClone(obj)YesModern, preserves types
JSON.parse(JSON.stringify(obj))YesLoses functions, Date, undefined
_.cloneDeep(obj) (lodash)YesThe most reliable and cross-platform

Summary

PropertyShallow copyDeep copy
Copies only the top levelYesNo
Copies nested objectsNo (references)Yes
Changes to nested data affect the originalYesNo
Examples{ ...obj }, Object.assign()structuredClone(), _.cloneDeep()

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.