|
1 | 1 | //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 |
4 | 5 | const b=a; //Cloned Object |
5 | 6 | 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 | + |
9 | 12 | //Spread Operator |
10 | 13 | const c={...a}; |
11 | 14 | 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 | + |
14 | 18 | //Assign Operator |
15 | 19 | const d=Object.assign({},a); |
16 | 20 | 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