Create a deep copy of an object with nested properties
Quick Answer
Deep cloning creates a fully independent copy of a JavaScript object, including all nested objects and arrays, so mutations to the clone do not affect the original.
1function deepClone(obj) {
2 if (obj === null || typeof obj !== 'object') return obj;
3 if (obj instanceof Date) return new Date(obj.getTime());
4 if (obj instanceof Array) return obj.map(item => deepClone(item));
5 if (obj instanceof Object) {
6 const clonedObj = {};
7 for (const key in obj) {
8 if (obj.hasOwnProperty(key)) {
9 clonedObj[key] = deepClone(obj[key]);
10 }
11 }
12 return clonedObj;
13 }
14}Deep cloning creates a completely independent copy of an object, including all nested objects and arrays. This prevents unintended mutations when working with complex data structures. Unlike shallow copying with the spread operator or Object.assign, deep cloning recursively copies all levels of nested properties.
It loses undefined properties, converts Date objects to strings, and throws on values that are not JSON-serialisable such as functions or BigInt.
Yes. structuredClone() is now available in all major browsers and Node 17+. It handles more types than JSON but does not copy functions or class prototypes.
Keep a WeakMap of already-visited objects and return the existing clone if the same reference is encountered again.
This free javascript code snippet for deep clone object is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement deep clone object quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.