How to deep clone an object in JavaScript
Creating complete copies of nested objects is a common requirement when working with complex data structures in JavaScript applications.
As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development, I’ve encountered this challenge countless times when managing component state and configuration objects.
The most modern and reliable solution is using the structuredClone() method, which creates true deep copies of objects.
This method handles nested objects, arrays, and most data types correctly.
Use structuredClone() to create a complete deep copy of an object with all nested properties.
const original = { user: { name: 'John', preferences: { theme: 'dark' } } }
const deepCopy = structuredClone(original)
The structuredClone() method creates a deep copy of the object, meaning all nested objects and arrays are also cloned rather than just referenced. This ensures that modifications to the cloned object won’t affect the original object or vice versa. The method handles complex data types like Dates, RegExp, Maps, and Sets correctly, making it superior to JSON-based cloning methods.
Best Practice Note:
This is the same approach we use in CoreUI components when duplicating complex configuration objects. For older browser support, you can use JSON.parse(JSON.stringify(obj)) as a fallback, though it has limitations with functions and special object types.



