![]() |
In general, cloning means copying one value to another. In JavaScript, there are two types of cloning, i.e. Deep clone and shallow clone. This article is about Deep clones and we will learn about Deep clones. Cloning is a concept that can happen in any data type i.e. it might be a primitive data type (like string, number) or composite data types like arrays and JavaScript. Deep Clone: Deep clone is a technique that is used to duplicate everything whenever we are cloning arrays and objects in JavaScript in order to avoid data loss.
Example 1: As in the below example, the data is becoming corrupted if we change one object value then it is reflected in other objects also that is the reason in order to avoid this problem we use Deep Clone. Javascript
Output: First name is GeeksForGeeks Second name is GeeksForGeeks Example 2: As in the below example, the data is becoming corrupted if we change one object value then it is reflected in other objects also. Javascript
Output: New Employee, { eid: 'E102', ename: 'Beck', eaddress: 'New York', salary: 50000 } Old Employee, { eid: 'E102', ename: 'Beck', eaddress: 'New York', salary: 50000 } Approach: Now we will create our own custom function to deep clone an object.
Example: This example shows the use of the above-explained approach. Javascript
Output: { name: { firstName: 'alice', lastName: null }, address: { number: 12345, country: 'London', pincode: 208027 }, email: '[email protected]', hobbies: ['singing', 'dancing', 'music'] } { name: { firstName: 'alice', lastName: null }, address: { number: 12345, country: 'india', pincode: 208027 }, email: '[email protected]', hobbies: ['singing', 'dancing', 'music'] } { a: null, b: true } { a: 'gfg', b: true } Explanation: Even after modifying the obj the data is safe in deepCopiedObject and deepCopiedObjectTwo and doesn’t get mutated. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |