Ad space (banner)
🟨JavaScript Lessons
Lesson 41 / 69

The Difference Between Shallow Copy and Deep Copy

In this lesson you'll learn the difference between shallow copy and deep copy so you can avoid unexpected bugs when duplicating an object. This is for people searching "JavaScript shallow copy vs deep copy" or "JavaScript how to copy an object."

A shallow copy duplicates only "the outermost container," leaving any nested inner objects shared with the original. A deep copy duplicates everything, all the way down, so changing the copy doesn't affect the original data. The spread syntax { ...original } creates a shallow copy, and JSON.parse(JSON.stringify(...)) creates a simple deep copy.

The sample code shows how modifying the nested part (address.city) of shallow, a shallow copy of an object called original made with { ...original }, also ends up changing original itself. Meanwhile, modifying deep, a deep copy made with JSON.parse(JSON.stringify(original)), has no effect on the original data.

A bug where "I thought I copied it, but the original data got changed too" is a common beginner stumbling block that happens without understanding this difference. When duplicating an object, being mindful of this distinction is essential, or it can be the source of unexpected bugs. Also be careful: a deep copy using JSON can't be used for data that contains functions or undefined values.

In real development, being able to correctly choose the right kind of copy matters when, for example, temporarily editing form input data while wanting to retain the original data. The more an application relies on state management, the more important understanding this difference becomes.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)