Typorithm · easy

Shallow vs Deep Copy

shallow-vs-deepinterview-questionsspreadobject-assignreferences
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Shallow vs Deep Copy

0%

Copy & Equality

Spread { ...obj } and Object.assign({}, obj) make shallow copies: top-level fields are copied, but nested objects are shared references. Mutating a nested object through the copy also mutates the original.

A shallow copy duplicates only the outermost layer. Both { ...obj } and Object.assign({}, obj) produce a new object whose nested objects are the *same* references as the source.

Primitive top-level fields (strings, numbers, booleans) are copied by value, so reassigning them on the copy does not affect the original.

But nested objects and arrays are shared: shallow.nested.x = 1 mutates obj.nested.x too, because both point at one object. A deep copy clones every level, breaking that sharing.

01

{ ...obj } and Object.assign({}, obj) copy only the top level.

02

Nested objects stay as shared references in a shallow copy.

03

A deep copy clones every nested level, so mutations stay isolated.

const obj = { name: "Ada", nested: { x: 0 } }
const shallow = { ...obj }
const copy = Object.assign({}, obj)

shallow.nested.x = 1
console.log(obj.nested.x) // 1 — original mutated!

Read the implementation

Connect each part of the code to the concept before you type.

1. Spread copy

The spread { ...obj } copies only the top-level fields into a new object.

const shallow = { ...obj }

2. Object.assign copy

Object.assign({}, obj) also copies just the top level, exactly like spread.

const copy = Object.assign({}, obj)

3. Shared nested mutation

shallow.nested is the same reference as obj.nested, so writing through it changes both.

shallow.nested.x = 1

4. The pitfall

The original sees x become 1 because the nested object was never cloned, only its reference.

console.log(obj.nested.x) // 1 — original mutated!

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Shallow vs Deep Copy: Lesson & Practice · Typorithm | ApplyDjinn