JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
Prev
javascript
mid
objects

What is the difference between shallow copy and deep copy in JavaScript, and how do you create each?

objects
arrays
spread-operator
structuredClone
cloning
immutability
Quick Answer

A shallow copy duplicates only top-level properties while nested objects share references; a deep copy recursively duplicates all nested objects creating fully independent copies.

Detailed Explanation

Shallow Copy:

  • Creates a new object but nested references point to same memory locations
  • Changes to nested objects affect both copies

Methods that create shallow copies:

  • Spread operator ({...obj}, [...arr])
  • Object.assign({}, obj)
  • Array.prototype.slice()
  • Array.from()

Deep Copy:

  • Creates completely independent copy where no references are shared
  • Changes to one don't affect the other

Methods for deep copy:

  1. structuredClone() (Recommended - ES2022+)

    • Handles Date, Map, Set, ArrayBuffer, Error, circular references
    • Cannot clone: functions, Symbols, DOM nodes
  2. JSON.parse(JSON.stringify()) (Legacy)

    • Simple but lossy: drops undefined, functions, Symbols
    • Fails on circular references
    • Converts Date to string
  3. lodash _.cloneDeep() - Most comprehensive, handles edge cases

Code Examples

Shallow copy problem
const original = { 
  name: 'John', 
  address: { city: 'NYC', zip: '10001' } 
};

// Shallow copy with spread operator
const shallow = { ...original };

// Modifying top-level works as expected
shallow.name = 'Jane';
console.log(original.name); // 'John' - unchanged

// But nested objects are shared!
shallow.address.city = 'LA';
console.log(original.address.city); // 'LA' - original mutated!

// Same issue with Object.assign
const shallow2 = Object.assign({}, original);
shallow2.address.zip = '90001';
console.log(original.address.zip); // '90001' - mutated again!

Resources

MDN - Deep copy

docs

MDN - structuredClone

docs

JavaScript.info - Object copying

article

Related Questions

How does the 'this' keyword work in JavaScript?

mid
this

What is a closure in JavaScript and why are they useful?

mid
closures
Previous
How does the 'this' keyword work in JavaScript?