#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 33 of 50medium

What is the difference between shallow and deep copy?

Understanding object copying in JavaScript.

What You'll Learn

  • Shallow vs deep copy
  • Methods for each
  • Common pitfalls

Shallow Copy

Copies only the first level. Nested objects are still referenced.

code.jsJavaScript
const original = {
  name: 'John',
  address: { city: 'NYC' }
};

// Shallow copy methods
const copy1 = { ...original };
const copy2 = Object.assign({}, original);

copy1.name = 'Jane';           // Doesn't affect original
copy1.address.city = 'LA';     // DOES affect original!

console.log(original.address.city); // 'LA'

Deep Copy

Copies all levels. No shared references.

code.jsJavaScript
// Method 1: JSON (limited)
const deepCopy1 = JSON.parse(JSON.stringify(original));
// ⚠️ Doesn't work with: functions, undefined, Date, RegExp, Map, Set

// Method 2: structuredClone (modern)
const deepCopy2 = structuredClone(original);
// ⚠️ Doesn't work with: functions, DOM elements

// Method 3: Recursive function
function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (Array.isArray(obj)) return obj.map(deepClone);

  const clone = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clone[key] = deepClone(obj[key]);
    }
  }
  return clone;
}

Arrays

code.jsJavaScript
const arr = [1, [2, 3], { a: 4 }];

// Shallow
const shallow = [...arr];
const shallow2 = arr.slice();

// Deep
const deep = structuredClone(arr);