Deep Copy vs Shallow Copy0%

Deep Copy vs Shallow Copy

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Deep Copy vs Shallow Copy in Modern JavaScript

In JavaScript, primitive values (numbers, strings, booleans, symbols, null, undefined) are copied by value, whereas objects (including arrays, functions, and plain objects) are referenced by memory address. Misunderstanding the boundary between shallow copies and deep copies is one of the most frequent causes of state mutation bugs.


1. References vs. Copies

JavaScript
const userA = { name: 'Alice', score: 95 };
const userB = userA; // COPIES REFERENCE ONLY!
 
userB.score = 100;
console.log(userA.score); // 100! userA was mutated!
Output
Variable Reference:
userA ───┐
▼
[ { name: 'Alice', score: 100 } in Heap Memory ]
▲
userB ───┘

2. Shallow Copy: Methods and Limitations

A shallow copy creates a new outer object or array, but any nested objects or arrays inside it are still shared references.

Methods for Shallow Copying

  1. 1
    Object Spread Operator: { ...source }
  2. 2
    Array Spread Operator: [ ...sourceArray ]
  3. 3
    Object.assign(): Object.assign({}, source)
  4. 4
    Array.prototype.slice(): sourceArray.slice()
JavaScript
const original = {
title: 'Mastering JavaScript',
author: { name: 'Sarah', country: 'Canada' } // Nested Object
};
 
// Shallow copy
const copy = { ...original };
 
copy.title = 'Advanced JavaScript'; // Safe! Only copy.title changes.
copy.author.country = 'Germany'; // DANGER! Mutates BOTH original and copy!
 
console.log(original.author.country); // 'Germany' (Shared reference!)
Output
Shallow Copy Memory Map:
original ──► [ Object 1: title: 'Mastering JS' ] ──┐
▼
[ Nested author object ]
▲
copy ──► [ Object 2: title: 'Advanced JS' ] ──┘

3. Deep Copying: Modern structuredClone()

A deep copy recursively duplicates every level of nested objects and arrays, ensuring complete isolation in memory.

The Modern Standard: structuredClone()

Introduced natively in modern JavaScript (Node.js 17+ and all modern browsers):

JavaScript
const order = {
id: 'ORD-9812',
items: [{ sku: 'KB-01', qty: 2 }],
createdAt: new Date()
};
 
// TRUE DEEP COPY:
const deepClonedOrder = structuredClone(order);
 
deepClonedOrder.items[0].qty = 5;
console.log(order.items[0].qty); // 2! Original is completely untouched!
console.log(deepClonedOrder.createdAt instanceof Date); // true! Preserves Date objects!

Features of structuredClone():

  • Handles nested objects and arrays to any depth.
  • Supports cyclic references (objects referencing themselves).
  • Preserves Date, RegExp, Map, Set, and ArrayBuffer instances.
  • Limitation: Does not clone functions or DOM nodes (throws DataCloneError).

4. The Legacy JSON Hack (and its gotchas)

JavaScript
const legacyCopy = JSON.parse(JSON.stringify(original));

Critical Pitfalls of JSON.parse(JSON.stringify()):

  • Discards functions and methods.
  • Converts Date objects into ISO strings.
  • Converts NaN and Infinity to null.
  • Throws errors on circular references.
  • Strips undefined values and Symbol keys.

5. Summary Cheat Sheet

TechniqueCopy DepthPreserves Dates/RegExp?Handles Circular Refs?Clones Functions?
Object.assign({}, obj)ShallowYes (references)N/ACopies reference
{ ...obj }ShallowYes (references)N/ACopies reference
JSON.parse(JSON.stringify())DeepNo (converts to string)Throws ErrorDrops functions
structuredClone(obj)DeepYesYesThrows Error

Interactive Quiz

Practice Quiz

Question 1
What happens when you modify a nested object property inside a shallow copy created with {...original}?
Question 2
What native modern JavaScript API provides true deep cloning out of the box?
Question 3
What is a major limitation of using JSON.parse(JSON.stringify(obj)) to clone objects?
Question 4
Which of the following creates a shallow copy of an array?
Question 5
What error occurs if you pass an object containing a function to structuredClone()?
Next Lesson

Object.keys, Object.values, Object.entries

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext