JavaScript·100 questions

QUESTION: How to deeply copy an object?

Answer

Creating a deep copy of an object in JavaScript is necessary when you need to completely duplicate a complex data structure with all nested objects and arrays. This guarantees that any changes in the copy will not affect the original object.

The most modern and preferred method today is using the built-in structuredClone function. It correctly handles most built-in data types, preserves circular references, and is part of the browser and Node.js standards.

A historically popular approach with serialization via JSON.parse(JSON.stringify(obj)) is still found in other people's code, but has critical limitations. It completely removes function methods, cannot work with special types like Map, Set, Date, and crashes with an error on circular references.

In large projects with an old codebase, proven third-party libraries are often used. For example, the cloneDeep utility method from the popular Lodash ecosystem reliably solves all deep cloning problems for many years.

In extreme cases, when specific business logic or strict control over copied types is required, developers write their own recursive functions for traversing object properties.

Make sure you really need a deep copy, not a shallow reference duplication.
Call the built-in structuredClone function and pass the original object to it as an argument.
Save the result of the function execution into a new variable for further use.
Verify the independence of modified nested fields in the new object relative to the original.

It is important to always remember that the regular spread operator or the Object.assign method are categorically unsuitable for deep copying. They perform exclusively shallow copying and duplicate references to all internal nested objects.

Was this answer helpful?

More questions in this topic

Related questions from other topics