Differences: Shallow and Deep Copies in JavaScript

Have you ever tried to create a duplicate of an object in JavaScript, but the output wasn’t what you expected? If so, this article will discuss the different techniques for cloning and how to correctly utilize them. This knowledge will help guarantee that you get the correct results whenever you use the clone command.

In JavaScript, we can also create shallow copies and deep copies of objects. Let’s dive into what each of these concepts means in JavaScript.

Shallow Copy

A shallow copy in JavaScript creates a new object that contains references to the same memory locations as the original object. This means that if any changes are made to the copied object, the original object is also affected.

In JavaScript, there are several ways to create a shallow copy:

Object.assign()

The Object.assign() method copies all enumerable properties of an object to a new object. It takes one or more source objects and a target object. The target object is the object that will be modified and returned. Here’s an example:

let originalObj = { name: "John", age: 30 };
let copiedObj = Object.assign({}, originalObj);

copiedObj.age = 40;

console.log(originalObj.age); // Output: 40

As you can see, changing the age property of the copied object also changes the age property of the original object.

Spread Operator

The spread operator (...) can also be used to create a shallow copy of an object. This operator spreads the properties of an object into a new object. Here’s an example:

let originalObj = { name: "John", age: 30 };
let copiedObj = { ...originalObj };

copiedObj.age = 40;

console.log(originalObj.age); // Output: 40

Again, changing the age property of the copied object also changes the age property of the original object. 

Deep Copy

A deep copy creates a new object with all the properties and sub-properties of the original object. This means that any changes made to the copied object will not affect the original object.

In JavaScript, there are several ways to create a deep copy:

JSON.parse() and JSON.stringify()

The easiest way to create a deep copy of an object is to use JSON.parse() and JSON.stringify(). Here’s an example:

let originalObj = { name: "John", age: 30, address: { city: "New York", state: "NY" } };
let copiedObj = JSON.parse(JSON.stringify(originalObj));

copiedObj.address.city = "Los Angeles";

console.log(originalObj.address.city); // Output: New York

As you can see, changing the city property of the copied object does not affect the city property of the original object.

Recursion

Another way to create a deep copy is to use recursion to copy all the properties of the original object and any sub-objects. Here’s an example:

function deepCopy(obj) {
  let copiedObj = Array.isArray(obj) ? [] : {};

  for (let key in obj) {
    if (typeof obj[key] === "object" && obj[key] !== null) {
      copiedObj[key] = deepCopy(obj[key]);
    } else {
      copiedObj[key] = obj[key];
    }
  }

  return copiedObj;
}

let originalObj = { name: "John", age: 30, address: { city: "New York", state: "NY" } };
let copiedObj = deepCopy(originalObj);

copiedObj.address.city = "Los Angeles";

console.log(originalObj.address.city); // Output: New York

In this example, the deepCopy() function recursively copies all the properties and sub-properties of the original object. Any changes made to the copied object do not affect the original object. 

Conclusion

In conclusion, understanding the difference between shallow copy and deep copy in JavaScript is important for proper object manipulation and memory management.

A shallow copy creates a new object that shares the same memory references as the original object. Any changes made to the shallow copy or original object will affect both objects. A shallow copy can be useful for creating references to existing objects without consuming more memory.

On the other hand, a deep copy creates a new object that is entirely independent of the original object. Any changes made to the deep copy will not affect the original object and vice versa. A deep copy can be useful for creating entirely new objects that are not dependent on the original object.

The choice between shallow copy and deep copy depends on the requirements of the code and the desired outcome. A shallow copy is useful when dealing with large objects that need to be referenced multiple times, while a deep copy is useful when creating new, independent objects that are not dependent on the original object.


Source link