How to use Object.assign() method to Deep clone In Javascript
The Object.assign() method is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.
Syntax:
Object.assign(target, ...sources);
Example: In this example, we are using Object.assign().
Javascript
let student1 = { name: "Manish" , company: "Gfg" } let student2 = Object.assign({}, student1); student1.name = "Rakesh" console.log( "student 1 name is" , student1.name) console.log( "student 2 name is " , student2.name); |
Output
student 1 name is Rakesh student 2 name is Manish
How to Deep clone in JavaScript ?
In general, cloning means copying one value to another. In JavaScript, we do cloning i.e. copying one value to another using JavaScript. To be more precise there are two types of cloning in JavaScript. As a programmer, it might be a beginner or veteran he/she should be able to know the differences between Deep clone and shallow clone. As this article is about Deep clones we will study detail about Deep clones.
Contact Us