Deep & Shallow Copy Javascript
- What is a Shallow Copy of an object?
- When one object holds the reference to another object this is called a shallow copy.
- What is a Deep Copy of an object?
- When we completely clone an object into an another variable that is called a deep copy.
- We don't have any references to the original.
How to Deep Copy / clone an object?
let user = {
name: "Chaitanya",
age: 22,
};
const objClone = Object.assign({}, user);
objClone.name = "Shahare";
console.log(user, objClone);
// OR ------------------
const objClone = JSON.parse(JSON.stringify(user));
objClone.name = "Shahare";
console.log(user, objClone);
// OR -------------------
const objClone = { ...user };
objClone.name = "Shahare";
console.log(user, objClone);
``