JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Objects & Copying

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 - HTML spec, widely supported)

    • 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 problemJavaScript
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!

Real-World Applications

Use Cases

Redux State Updates

Creating shallow copies of state slices before modifying nested properties to maintain immutability in reducers

Undo/Redo

Storing deep copies of application state at each step for history navigation and state snapshots

API Request Building

Cloning base request configurations before adding endpoint-specific options like headers or query params

Mini Projects

Undo/Redo System

beginner

Build a text editor state manager using structuredClone to create history snapshots for undo and redo

Deep Diff Utility

intermediate

Build a function that compares two objects recursively and returns the differences as a structured report

Industry Examples

Immer

Provides immutable state updates using a draft proxy pattern instead of manual shallow/deep copying

Redux Toolkit

Uses Immer internally so reducers can write mutating logic that automatically produces immutable updates

MDN

structuredClone is supported in all modern browsers (Chrome 98+, Firefox 94+, Safari 15.4+) and Node.js 17+

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?
Next
What is the difference between microtasks and macrotasks in JavaScript?
PrevNext