Shallow and Deep Copy in JavaScript: Understanding the Difference

Shallow and Deep Copy in JavaScript: Understanding the Difference

As a JavaScript developer, you may have heard the terms "shallow copy" and "deep copy" being used interchangeably. While both involve creating a duplicate of an object or array, they differ in how they are copied and can lead to different outcomes in your code. In this blog post, we will explore the differences between shallow and deep copy in JavaScript and provide examples to illustrate their usage.

Shallow Copy

A shallow copy creates a new object or array that references the original object or array. This means that any changes made to the copy will also be reflected in the original object or array. In other words, a shallow copy is only one level deep and does not create a new copy of objects or arrays.

Here's an example of a shallow copy in JavaScript:

const person = {
  name: 'John Doe',
  city: 'New York    
};

const copiedPerson = person; // shallow copy

person.city = 'London';

console.log(person) // { name: 'John Doe', city: 'London' };
console.log(copiedPerson) // { name: 'John Doe', city: 'London' };

Deep Copy

A deep copy creates a new object or array that is an exact duplicate of the original object or array. This means that any changes made to the copy will not affect the original object or array. In other words, a deep copy is a full and independent copy of an object or array, including any nested objects or arrays.

Here's an example of a deep copy in JavaScript:

const person = {
  name: 'John Doe',
  city: 'New York'    
};

const copiedPerson = { ...person }; // deep copy
// const copiedPerson = Object.assign({}, person); (another way)

person.city = 'London';

console.log(person) // { name: 'John Doe', city: 'London' };
console.log(copiedPerson) // { name: 'John Doe', city: 'New York' };

Nested Objects

Let's consider another example of nested objects:

const person = {
    name: 'John',
    address: {
        city: 'New York',
        country: 'USA'
    }
};

const firstCopyOfPerson = person;
const secondCopyOfPerson = { ...person };
// const secondCopyOfPerson = Object.assign({}, person);

person.name = 'Nick';
person.address.city = 'Los Angeles';

console.log(person); 
// { name: 'Nick', address: { city: 'Los Angeles', country: 'USA' }}

console.log(firstCopyOfPerson);
// { name: 'Nick', address: { city: 'Los Angeles', country: 'USA' }}

console.log(secondCopyOfPerson);
// { name: 'John', address: { city: 'Los Angeles', country: 'USA' }}

In this example, we can notice the nested object is shallowly copied even though we are using the spread operator (or using Object.assign() method). We can conclude from the above example that the spread operator (or Object.assign()) creates a deep copy of top-level data and a shallow copy of nested data. To create a deep copy of a nested object or array, we can use the JSON.parse(JSON.stringify()) method. This method creates a deep copy of the original object by first converting it to a JSON string and then parsing it back into a new object.

Here is an example of creating a deep copy of the nested object:

const person = {
  name: "John",
  address: {
    city: "New York",
    state: "NY",
  },
};
const deepCopyPerson = JSON.parse(JSON.stringify(person));

person.name = "Mary";
person.address.city = "San Francisco";

console.log(person); 
// {name: "Mary", address: {city: "San Francisco", state: "NY"}}

console.log(deepCopyPerson); 
// {name: "John", address: {city: "New York", state: "NY"}}

When to Use Shallow vs. Deep Copy

Knowing when to use shallow or deep copy depends on your specific use case. If you only need to make changes to the top-level properties of an object or array, a shallow copy is sufficient. However, if you need to make changes to nested objects or arrays without affecting the original object or array, a deep copy is necessary.

In general, it's a good practice to use the shallow copy for performance reasons, as it is less resource-intensive than a deep copy. However, if you need to make a complete and independent copy of an object or array, a deep copy is the way to go.

Did you find this article valuable?

Support Zeeshan Ashraf by becoming a sponsor. Any amount is appreciated!