DEV Community

Cover image for Shallow Copy vs Deep Copy in JavaScript
Homayoun
Homayoun

Posted on

Shallow Copy vs Deep Copy in JavaScript

When working with objects and arrays in JavaScript, you often need to copy data. But not all copies are the same! There are two types:

  • Shallow Copy
  • Deep Copy

Let’s understand what they mean, with easy examples.

Image description

What is a Shallow Copy?

A shallow copy copies only the first level of an object or array.

If the object has nested objects, it does not create a full new copy.

Instead, it just copies the reference (address) to the nested objects.

Example:

const original = {
  name: 'Ali',
  address: {
    city: 'Tehran'
  }
};

// Shallow copy using spread operator
const shallow1 = { ...original };

// Or using Object.assign
const shallow2 = Object.assign({}, original);

// Change in shallow copy
shallow1.address.city = 'Shiraz';

console.log(original.address.city); // Output: 'Shiraz'
Enter fullscreen mode Exit fullscreen mode

Why?

Because both shallow1.address and original.address point to the same inner object.

Image description

What is a Deep Copy?

A deep copy copies everything, including all nested objects.

It creates a full, independent copy. Changing one object will not affect the other.

Example:

const original = {
  name: 'Ali',
  address: {
    city: 'Tehran'
  }
};

const deep = JSON.parse(JSON.stringify(original));

// Change in deep copy
deep.address.city = 'Isfahan';

console.log(original.address.city); // Output: 'Tehran'
Enter fullscreen mode Exit fullscreen mode

Why?

Because deep and original are fully separated. No shared parts.

How to Create Copies

✅ Shallow Copy Methods

For objects:

const copy1 = { ...original };
const copy2 = Object.assign({}, original);
Enter fullscreen mode Exit fullscreen mode

For arrays:

const copy1 = [...originalArray];
const copy2 = originalArray.slice();
Enter fullscreen mode Exit fullscreen mode

✅ Deep Copy Methods

  1. Using JSON (easy but limited):
const deepCopy = JSON.parse(JSON.stringify(obj));
Enter fullscreen mode Exit fullscreen mode

⚠️ This will remove functions, Dates, undefined, Map, Set, etc.

  1. Using structuredClone() (modern and accurate):
const deepCopy = structuredClone(obj);
Enter fullscreen mode Exit fullscreen mode

✅ Works in modern browsers and supports many data types.

  1. Using Lodash (library):
import cloneDeep from 'lodash/cloneDeep';
const deepCopy = cloneDeep(obj);
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

  • Use shallow copy when your object is simple and doesn’t have inner objects.
  • Use deep copy when you want full independence between the copy and original.

Top comments (0)