Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Explain Deep cloning an object in JavaScript with an example.
Deep cloning creates a completely independent copy of an object, including all nested properties. Unlike shallow copying, changes to the cloned object don't affect the original.
Shallow vs Deep Copy Problem
With shallow copying, nested objects are shared between original and copy:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shallow Copy Problem</title>
</head>
<body>
<script>
let original = {
name: "John",
address: {
city: "New York",
country: "USA"
}
};
// Shallow copy using Object.assign
let shallowCopy = Object.assign({}, original);
// Modify nested object
shallowCopy.address.city = "Los Angeles";
console.log("Original city:", original.address.city);
console.log("Shallow copy city:", shallowCopy.address.city);
</script>
</body>
</html>
Original city: Los Angeles Shallow copy city: Los Angeles
Using JSON.parse() and JSON.stringify() Method
The most common approach for deep cloning uses JSON methods:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Deep Clone Example</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 16px;
font-weight: 500;
color: rebeccapurple;
margin: 10px 0;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Deep Cloning an Object in JavaScript</h1>
<div class="result" id="result"></div>
<button onclick="demonstrateDeepClone()">CLICK HERE</button>
<h3>Click the button to see deep clone in action</h3>
<script>
let obj = {
firstName: "Rohan",
lastName: "Sharma",
age: 22,
rollNo: "A12",
address: {
city: "Delhi",
country: "India"
}
};
// Deep clone using JSON methods
let deepClone = JSON.parse(JSON.stringify(obj));
function demonstrateDeepClone() {
const resultDiv = document.getElementById("result");
// Modify original object
obj.firstName = "Mohit";
obj.address.city = "Mumbai";
resultDiv.innerHTML =
"<strong>After modifying original:</strong><br>" +
"obj.firstName = " + obj.firstName + "<br>" +
"obj.address.city = " + obj.address.city + "<br><br>" +
"<strong>Deep clone remains unchanged:</strong><br>" +
"deepClone.firstName = " + deepClone.firstName + "<br>" +
"deepClone.address.city = " + deepClone.address.city;
}
</script>
</body>
</html>
Using structuredClone() Method
Modern browsers support the structuredClone() method for deep cloning:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>structuredClone Example</title>
</head>
<body>
<script>
let original = {
name: "Alice",
hobbies: ["reading", "swimming"],
profile: {
age: 25,
location: "Boston"
}
};
// Using structuredClone (modern approach)
let clone = structuredClone(original);
// Modify clone
clone.name = "Bob";
clone.hobbies.push("cycling");
clone.profile.age = 30;
console.log("Original name:", original.name);
console.log("Clone name:", clone.name);
console.log("Original hobbies:", original.hobbies);
console.log("Clone hobbies:", clone.hobbies);
console.log("Original age:", original.profile.age);
console.log("Clone age:", clone.profile.age);
</script>
</body>
</html>
Original name: Alice Clone name: Bob Original hobbies: ["reading", "swimming"] Clone hobbies: ["reading", "swimming", "cycling"] Original age: 25 Clone age: 30
Comparison of Methods
| Method | Handles Functions | Handles Dates | Browser Support |
|---|---|---|---|
JSON.parse(JSON.stringify()) |
No | No (converts to string) | Universal |
structuredClone() |
No | Yes | Modern browsers |
Limitations
Both methods have limitations with functions, symbols, and certain object types:
let obj = {
func: function() { return "hello"; },
date: new Date(),
undefined: undefined,
symbol: Symbol("test")
};
// JSON method loses functions and symbols
let jsonClone = JSON.parse(JSON.stringify(obj));
console.log("JSON clone:", jsonClone);
// structuredClone preserves dates but not functions
let structClone = structuredClone(obj);
console.log("Structured clone:", structClone);
JSON clone: { date: "2024-01-01T12:00:00.000Z" }
Structured clone: { date: 2024-01-01T12:00:00.000Z, undefined: undefined }
Conclusion
Use JSON.parse(JSON.stringify()) for simple objects or structuredClone() for better type preservation. Deep cloning ensures complete independence between original and copied objects.
Advertisements
