JavaScript Object Copying: Shallow Copy vs Direct Assignment
Talat Hussain
Reactjs | Nodejs | Expressjs | Nestjs| Socketio | Gsap | Three.js| As a web developer, my goal is to create a customized, beautiful website that meets the client's needs and reflects their brand identity
1) Shallow Copy with an Empty Target Object :
Create a new object as the target and copy properties from the source. - Changes to the source object won't affect the copied object.
Example:
const first = {"name": "Ali"};
const sec = Object.assign({}, first);
first.name = "Ahmad";
console.log("first:", first); // Output: { "name": "Ahmad" }
console.log("Second:", sec); // Output: { "name": "Ali" }
2) Direct Assignment:
Copying an object without creating a new object.Changes to the source object affect the copied object because both reference the same data.
Example:
const first = {"name": "Ali"};
const sec = Object.assign(first);
first.name = "Ahmad";
console.log("first:", first); // Output: { "name": "Ahmad" }
console.log("Second:", sec); // Output: { "name": "Ahmad" }