Back to all posts

Shallow Copy vs Deep Copy in JavaScript


When working with arrays and objects in JavaScript, it’s crucial to understand the differnce between shallow copying and deep copying. This knowledge can help you avoid unexpected behavior in your code and manage data more effectively. Let’s dive into these concepts with example.

Shallow Copy

A shallow copy creates a new array or object but the nested objects or array within it are still reference to the original. This mean changes to nested structures will affect both the copy and the original.

Examples of Shallow Copy

  1. Using the spread operator:
const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };

shallowCopy.a = 3;
shallowCopy.b.c = 4;

console.log(original);  // { a: 1, b: { c: 4 } }
console.log(shallowCopy);  // { a: 3, b: { c: 4 } }

2. Using `Object.assign()`:

const original = [1, [2, 3]];
const shallowCopy = Object.assign([], original);

shallowCopy[0] = 4;
shallowCopy[1][0] = 5;

console.log(original);  // [1, [5, 3]]
console.log(shallowCopy);  // [4, [5, 3]]

Deep Copy

A deep copy creates a new object or array and recursively copies all nested objects and arrays. this ensures that modification to the copy don’t affect the original.

Examples of Deep Copy

1.Using JSON methods:

const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));

deepCopy.a = 3;
deepCopy.b.c = 4;

console.log(original);  // { a: 1, b: { c: 2 } }
console.log(deepCopy);  // { a: 3, b: { c: 4 } }

Using a recursive function:

function deepCopy(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }

  let copy = Array.isArray(obj) ? [] : {};

  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      copy[key] = deepCopy(obj[key]);
    }
  }

  return copy;
}

const original = { a: 1, b: { c: [2, 3] } };
const deepCopied = deepCopy(original);

deepCopied.b.c[0] = 4;

console.log(original);  // { a: 1, b: { c: [2, 3] } }
console.log(deepCopied);  // { a: 1, b: { c: [4, 3] } }

When to Use Each

  • Use shallow copy when you only need to duplicate the top-level properties and don’t mind sharing references to nested objects.
  • Use deep copy when you need a completely independent clone of an object, including all nested objects and arrays.

Understanding the difference between shallow and deep copying is essential for managing complex data structures in JavaScript. By choosing the right approach, you can ensure your code behaves as expected and avoid unintended side effects when manipulating objects and arrays.