Javascript Shallow Copy Vs Deep
Javascript Shallow Copy Vs Deep
A shallow copy creates a new object or array, but it only copies the references to the nested
objects or arrays. This means that if the original object or array is modified, those changes will be
reflected in the shallow copy, especially for nested structures.
let company1Employees=['Arun','Bala'];
let company2Employees=company1Employees;
console.log(company1Employees)
console.log(company2Employees)
company1Employees.push('Jai')
console.log(company1Employees)
console.log(company2Employees)
let emp1={
name:'Rajan',
age:22
};
let emp2=emp1;
console.log(emp1)
console.log(emp2)
emp1.name="Siva"
console.log()
console.log(emp1)
console.log(emp2)
Deep Copy
A deep copy creates a new object or array and recursively copies all nested objects and arrays.
This means changes to the original object or array do not affect the deep copy.
let company1Employees=['Arun','Bala'];
let str=JSON.stringify(company1Employees);
let company2Employees=JSON.parse(str);
let company2Employees=JSON.parse(JSON.stringify(company1Employees))
company1Employees.push('Jai')
console.log(company1Employees)
console.log(JSON.stringify(company1Employees))
console.log(company2Employees)
let emp1={
name:'Rajan',
age:22
};
let emp2=JSON.parse(JSON.stringify(emp1));
emp2=Object.assign({},emp1)
emp2={...emp1}
console.log(emp1)
console.log(emp2)
emp1.name="Siva"
emp2.name="Raj"
console.log()
console.log(emp1)
console.log(emp2)
Summary of Differences
● Shallow Copy:
○ Copies the object or array structure but not the nested objects.
○ Changes to nested objects in the copy affect the original.
○ Easier and faster to create.
● Deep Copy:
○ Creates a completely independent copy of the entire structure, including nested
objects.
○ Changes to the copied structure do not affect the original.
○ More complex to implement and can be slower for large structures.