Back to library
📜JavaScriptjavascriptbeginner

Deep Clone Object

Create a deep copy of an object without references

objectsutilitiesimmutability

Code

1function deepClone(obj) {
2  // Handle null and non-object types
3  if (obj === null || typeof obj !== 'object') {
4    return obj;
5  }
6  
7  // Handle Date
8  if (obj instanceof Date) {
9    return new Date(obj.getTime());
10  }
11  
12  // Handle Array
13  if (Array.isArray(obj)) {
14    return obj.map(item => deepClone(item));
15  }
16  
17  // Handle Object
18  const clonedObj = {};
19  for (const key in obj) {
20    if (obj.hasOwnProperty(key)) {
21      clonedObj[key] = deepClone(obj[key]);
22    }
23  }
24  
25  return clonedObj;
26}
27
28// Usage example
29const original = { name: 'John', details: { age: 30 } };
30const copy = deepClone(original);
31copy.details.age = 31;
32console.log(original.details.age); // 30 (unchanged)

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.