Skip to content

Commit 531ba84

Browse files
authored
Update 4ShallowAndDeepCopy.js
1 parent 990ccc2 commit 531ba84

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

OOPS/4ShallowAndDeepCopy.js

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,30 @@
11
//SHALLOW COPY & DEEP COPY
2-
//SHALLOW COPY=changing the value of cloned object will reflect into original as well as because both are pointing to same reference object
3-
const a={id:101, name:"Sunanda"}; //Original Object
2+
//SHALLOW COPY=changing the value of cloned object will reflect into original as well as because both are pointing to same reference object.
3+
//It doesn't change the value of nested objects.
4+
const a={id:101, name:"Sunanda", marks: {eng:23, math:30}}; //Original Object
45
const b=a; //Cloned Object
56
b.id=102;
6-
console.log(a); //{ id: 102, name: 'Sunanda' }
7-
console.log(b); //{ id: 102, name: 'Sunanda' }
8-
//DEEP COPY=changing the value of object will not reflect into original object because both are pointing to different reference object
7+
console.log(a); //{ id: 102, name: 'Sunanda', marks: {eng:23, math:30}}
8+
console.log(b); //{ id: 102, name: 'Sunanda', marks: {eng:23, math:30}}
9+
b.marks.eng=39;
10+
console.log(a,b); //{ id: 102, name: 'Sunanda', marks: {eng:39, math:30}} { id: 102, name: 'Sunanda', marks: {eng:39, math:30}}
11+
912
//Spread Operator
1013
const c={...a};
1114
c.id=103;
12-
console.log(a); //{ id: 102, name: 'Sunanda' }
13-
console.log(c); //{ id: 103, name: 'Sunanda' }
15+
console.log(a); //{ id: 102, name: 'Sunanda' marks: {eng:39, math:30}}
16+
console.log(c); //{ id: 103, name: 'Sunanda' marks: {eng:39, math:30}}
17+
1418
//Assign Operator
1519
const d=Object.assign({},a);
1620
d.id=104;
17-
console.log(d); //{ id: 104, name: 'Sunanda' }
21+
console.log(d); //{ id: 104, name: 'Sunanda' marks: {eng:23, math:30}}
22+
23+
//DEEP COPY=changing the value of object will not reflect into original object because both are pointing to different reference object
24+
const a={id:101,name:'sunanda',marks:{math:23,eng:30}};
25+
const b= JSON.parse(JSON.stringify(a));
26+
b.id=102;
27+
b.name='mantu';
28+
b.marks.math=36;
29+
console.log(a,b);
30+
//{ id: 101, name: 'sunanda', marks: { math: 23, eng: 30 } } { id: 102, name: 'mantu', marks: { math: 36, eng: 30 } }

0 commit comments

Comments
 (0)