Skip to main content

shallow copy vs deep copy JavaScript

 In JavaScript, this is often achieved using methods like -

  • Object.assign({}, originalObject) or 
  • {...originalObject}
Live result URL:-  https://playcode.io/1944513

//Deep and Shallow Copy in JavaScript
//Example 1
let x = 'Hello world';
let y=x;
console.log("x is : ", x);
console.log("y is : ", y);

//Example 2
let obj ={
  name:'Anil'
}
let obj1 =obj;
obj1.name='Reena';

console.log("obj is : ", obj);
console.log("obj1 is : ", obj1);

//Example 3
let objA ={
  name:'Anil A'
}

let objB =Object.assign({},objA); //Type 1: this is called a 'Shallow Copy'.
It copies the memory location. Also, it copies only the main object.

//OR let objB ={...objA} //Type 2: this is also called a 'Shallow Copy'.
It copies the memory location. Also, it copies only the main object.
objB.name='Reena B';

console.log("objA is : ", objA);
console.log("objB is : ", objB);


//Example 4
let objX ={
  name:'Anil X',
  address: {
    city:'Noida',
    pin:201306,
    state:'UP'
  }
}

let objY =JSON.parse(JSON.stringify(objX)); //this is called a 'Deep Copy'.
It copies the nested objects
objY.address.city='Delhi'
console.log("objX is : ", objX);
console.log("objY is : ", objY);