MissionaryZeal

Shallow copy and Deep copy in JavaScript

In JavaScript, understanding the concepts of shallow copy and deep copy is crucial when dealing with arrays, especially when you want to duplicate an array without modifying the original. Let’s look at examples for both shallow copy and deep copy

Shallow Copy:

A shallow copy generates a new array by duplicating the reference variable of the original array. In this process, the new array retains references to the same memory locations as the elements in the original array. Consequently, any modifications made to elements within the new array impact the corresponding elements in the original array, as they share the same memory references. This interdependence arises from the fact that the shallow copy preserves the array’s reference structure, connecting the new array to the underlying objects in the original array.

Let’s taken an example:

let person = {
  name: "Kazi",
  age: 28
}

let newPerson = person
newPerson.name = "Roah"

console.log(newPerson) // { name: "Roah", age: 28 }
console.log(person)  //Hasin { name: "Roah", age: 28 }

Deep Copy:

A deep copy creates a new array and recursively copies all elements and nested elements, ensuring that the new array is entirely independent of the original. Including any nested arrays, making sure the new array is completely separate from the original. It creates a unique memory space for the new array, copying all the elements one by one. This way, both arrays exist independently, and any changes made to one won’t impact the other. If you delete one of the arrays, the other stays intact in the memory. We use JSON.parse() and JSON.stringify() to create a deep copy.

Let’s taken an example:


let person = {
  name: "Kazi",
  age: 28
}

let newPerson = JSON.parse(JSON.stringify(person))

newPerson.name = "Roha"
newPerson.age = 34

console.log(newPerson) // { name: "Roha", age: 34 }
console.log(person)  //   { name: "Kazi", age: 28 }
 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top