Implement Custom Function to Deep clone in JavaScript
Last Updated :
16 Mar, 2023
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
var obj1 = {
name: "Geeks",
company: "Gfg"
}
var obj2 = obj1;
obj1.name = "GeeksForGeeks"
console.log("First name is", obj1.name)
console.log("Second name is ", obj2.name);
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
var employee = {
eid: "E102",
ename: "Jack",
eaddress: "New York",
salary: 50000
}
var newEmployee = employee;
newEmployee.ename = "Beck";
console.log("New Employee", newEmployee);
console.log("Old Employee", employee);
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.
- We will make a function deepCopy which will take an object whose deep copy needs to be created as input and will return a deeply copied object.
- We will declare a result object which will store the final output.
- Check if the input object is:
- Null or undefined or an array or a function or not of the type object(for example - string, boolean number), then we will simply return the input
- If the input is of a type object then we will fetch the keys of the object using the Object.keys method and for each of the keys will again call the deepCopy function.
- Return result.
Example: This example shows the use of the above-explained approach.
JavaScript
// Declare object to be cloned
const obj = {
name: {
firstName: "alice",
lastName: null
},
address: {
number: 12345,
country: "London",
pincode: 208027
},
email: "[email protected]",
hobbies: ["singing", "dancing", "music"],
}
// Declare object to be cloned
const objTwo = {
a: null,
b: true
}
// Function to deep copy an existing object
// and return new object
function deepCopy(obj) {
// Declare object which will store the output
const result = {};
// If the object isnt of type object or
// object is null, undefined, is an Array
// or a function then no need to iterate
// over it and simply return it
if (typeof obj !== "object" ||
typeof obj === undefined ||
obj === null ||
Array.isArray(obj) ||
typeof obj == "function") {
return obj;
}
// Store the keys of the object
const keys = Object.keys(obj);
// Iterate through the keys of the
// object retrieved above
for (let key in keys) {
// Recursively iterate through each of the key.
result[keys[key]] = deepCopy(obj[keys[key]])
}
return result;
}
const deepCopiedObject = deepCopy(obj)
const deepCopiedObjectTwo = deepCopy(objTwo);
// Modifying property country
obj.address.country = "india"
console.log(deepCopiedObject)
console.log(obj)
objTwo.a = "gfg";
console.log(deepCopiedObjectTwo)
console.log(objTwo)
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.
Similar Reads
How to Deep clone in JavaScript?
Deep clone in JavaScript refers to creating a complete copy of an object, including all nested objects, ensuring that changes to the cloned object do not affect the original. Unlike shallow cloning, deep cloning requires copying all levels of the objectâs structure.1. Using Spread Operator to Deep C
2 min read
What are factory functions in JavaScript ?
In JavaScript, a factory function is a function that returns an object. It is a way of creating and returning objects in a more controlled and customizable manner. Factory functions are a form of design pattern that enables the creation of objects with specific properties and behaviors. Why it is us
2 min read
Copy Constructor in JavaScript
JavaScript does not have a built-in concept of a "copy constructor" like some other programming languages do. However, you can achieve the same result by using techniques for deep and shallow copying. In JavaScript, when you create an object, it is possible to make copies of that object. Shallow Cop
4 min read
How to clone a given regular expression in JavaScript ?
In this article, we will know How to clone a regular expression using JavaScript. We can clone a given regular expression using the constructor RegExp(). The syntax of using this constructor has been defined as follows:- Syntax: new RegExp(regExp , flags) Here regExp is the expression to be cloned a
2 min read
Explain the concepts of functional programming in JavaScript
Every program we write follows an approach or style of writing also referred to as a paradigm. Functional programming is a declarative programming paradigm (programming paradigm where we write code in such a way that it describes the result and not the approach). To understand functional programming
2 min read
How Inheritance works in Constructor Functions in JavaScript ?
Here, we will discuss inheriting a constructor function in JavaScript. Constructor functions define the prototype of the properties an object will contain. Using the constructor function, we can create a new object after passing the required parameters. Inheriting a previously defined constructor fu
3 min read
Function that can be called only once in JavaScript
In JavaScript, you can create a function that can be called only once by using a closure to keep track of whether the function has been called before. JavaScript closure is a feature that allows inner functions to access the outer scope of a function. Closure helps in binding a function to its outer
3 min read
How to Deep-Freeze an Object in JavaScript?
In JavaScript, freezing an object prevents it from being modified. This means you can no longer add, remove, or modify the properties of an object. However, by default, JavaScript's Object.freeze() only freezes the top level of an object, leaving nested objects or arrays mutable. To achieve immutabi
4 min read
JavaScript Function Call
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). This allows borrowing methods from other objects, executing them within a different context, overriding the default value, and passing arguments. Syntax: cal
2 min read
Pure Functions in JavaScript
A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed. Pure functions return consistent results for identical inputs.They do not modify external states or depend on mutable data.Often used with immutable data structures to ensure reliabi
2 min read