0% found this document useful (0 votes)
19 views

Javascript Shallow Copy Vs Deep

Uploaded by

nesamani373
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Javascript Shallow Copy Vs Deep

Uploaded by

nesamani373
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Shallow Copy

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.

EXAMPLE FOR ARRAY

Reference data type-array

let company1Employees=['Arun','Bala'];

let company2Employees=company1Employees;

console.log(company1Employees)

console.log(company2Employees)

company1Employees.push('Jai')

console.log(company1Employees)

console.log(company2Employees)

EXAMPLE FOR OBJECT

Reference data type-Object

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.

EXAMPLE FOR ARRAY

Deep copy-JSON //convert string

let company1Employees=['Arun','Bala'];

let str=JSON.stringify(company1Employees);

let company2Employees=JSON.parse(str);

let company2Employees=JSON.parse(JSON.stringify(company1Employees))

let let company2Employees=[...company1Employees]

company1Employees.push('Jai')

console.log(company1Employees)

console.log(JSON.stringify(company1Employees))

console.log(company2Employees)

EXAMPLE FOR OBJECT

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.

You might also like