Shallow and Deep Copies in JavaScript: Copying Objects

Learn how shallow and deep copies work, how to implement them, and how to avoid common pitfalls with object references.

🎯 Introduction

Frontend code works with objects constantly, but copying them can produce surprising results. Changing a copy may unexpectedly affect the original. This article explains object references, shallow copies, and deep copies, along with ways to implement them. Understanding these concepts helps you avoid mistakes and write more robust, flexible code.


🧩 What Is an Object Reference?

Primitive values and reference values differ in how they are represented in memory. In a simplified model, primitive values are stored on the stack, while objects are stored on the heap and accessed through references. Objects are reference values.

Storing Primitive Values

var a = 'xiaoming';
var b = 'libai';
var c = b;

Stack model

VariableTypeValue
aString"xiaoming"
bString"libai"
cString"libai"

Storing Reference Values

var a = { name: 'xiaoming', age: 18 };
var b = a;

Stack model

VariableTypeValue
aObject0x000001
bObject0x000001

Heap model

Addressname propertyage property
0x000001xiaoming18

⚠️ What Happens When You Assign an Object Directly?

Assigning an object to another variable copies its reference, rather than the object itself. Both variables refer to the same object, so changes made through either reference are visible through the other.

This can cause subtle bugs, especially when a complex object is used in several places. A mutation in one location affects every part of the application that uses the same object.


✂️ What Is a Shallow Copy?

A shallow copy copies an object's top-level properties. Primitive property values, such as strings and numbers, are copied as values. Properties containing objects or arrays retain references to those objects or arrays.

For example:

var obj1 = {
    name: 'Ming',
    hobby: ['basketball', 'soccer'],
};
var obj2 = Object.assign({}, obj1);
obj2.name = 'Hong';
obj2.hobby.push('swimming');

console.log(obj1.name); // Ming; changing a primitive property does not affect the original
console.log(obj1.hobby); // ["basketball", "soccer", "swimming"]; mutating the shared array affects the original

Changing obj2.name does not affect obj1, but mutating the shared hobby array also changes what you see through the original object.


🔨 How Do You Create a Shallow Copy?

Common approaches in JavaScript include:

  • Using Object.assign()
  • Using spread syntax (ES6; this article avoids that syntax)
  • Writing a function that copies properties in a loop

Example using Object.assign:

var source = { a: 1, b: { c: 2 } };
var copy = Object.assign({}, source);
console.log(copy.b === source.b); // true; both properties reference the same object
Use a shallow copy when all property values are primitives, or when nested values do not need to be independent.

🌊 What Is a Deep Copy?

A deep copy recursively copies every level of an object so the copy and the original are independent. Mutating one does not affect the other.

It copies both top-level properties and nested objects and arrays, all the way down to the innermost values.

🛠 How Do You Create a Deep Copy?

Common approaches recursively copy all properties:

  • Use JSON.parse(JSON.stringify(obj)). This is a simple, quick approach, but it cannot preserve functions, undefined, or circular references, among other limitations.
  • Write a recursive function that checks value types and copies each level.

Example using JSON:

var source = {
    a: 1,
    b: { c: 2 },
    d: function () {
        console.log('hello');
    },
};
var deepCopy = JSON.parse(JSON.stringify(source));
console.log(deepCopy); // { a: 1, b: { c: 2 } }; the function is omitted

Here is a simple recursive implementation:

function deepClone(obj) {
    if (obj === null) return null;
    if (typeof obj !== 'object') return obj;

    var copy = Array.isArray(obj) ? [] : {};

    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            copy[key] = deepClone(obj[key]);
        }
    }

    return copy;
}

var source = { a: 1, b: { c: 2 } };
var copy = deepClone(source);
copy.b.c = 3;
console.log(source.b.c); // 2; the objects are independent
A recursive deep copy must handle circular references to avoid endless recursion. In production projects, consider an established library such as Lodash's _.cloneDeep.

💡 Why Does the Difference Matter?

State management is important in frontend development. In React or Vue, copying objects incorrectly can prevent expected view updates or cause unintended changes to shared data.

Performance also matters. Deep copies can be expensive for large objects. Shallow copies are faster, but do not duplicate nested objects. Choose the approach that balances correctness and efficiency for your needs.


🧰 Practical Example: Updating an Object in an Array

Suppose you have an array of user objects and need to update one user's age.

If you make a shallow copy of the array, modifying a user object also affects the original array's data. A deep copy avoids this issue.

var users = [
    { id: 1, name: 'Ming', age: 18 },
    { id: 2, name: 'Hong', age: 20 },
];

var copiedUsers = JSON.parse(JSON.stringify(users));
copiedUsers[0].age = 19;

console.log(users[0].age); // 18; the original array is unaffected

❓ Knowledge Check

Q1: Does a shallow copy copy functions stored in an object? It copies the function references, rather than duplicating the functions. Both properties still reference the same function.

Q2: Why can't JSON.parse(JSON.stringify()) deep-copy functions? JSON does not support functions, so function-valued object properties are omitted during serialization.

Q3: Is there a simple way to detect circular references? You can use a WeakSet to track objects visited during traversal and detect cycles, preventing endless recursion.


🧪 Exercises

Exercise 1: Implement a shallow-copy function using Object.assign. Test how changing primitive properties and mutating reference-valued properties affect the original.

function shallowCopy(obj) {
    // Implement your solution here
}

var original = { name: 'Ming', hobby: ['basketball', 'soccer'] };
var copy = shallowCopy(original);
copy.name = 'Hong';
copy.hobby.push('swimming');

console.log(original.name); // ?
console.log(original.hobby); // ?

Exercise 2: Write a recursive deep-copy function that handles circular references without endless recursion. Test it with an object nested several levels deep.

function deepClone(obj, hash) {
    // Implement your solution here
}

var complexObj = { a: 1, b: { c: 2, d: { e: 3 } } };
var copy = deepClone(complexObj);
copy.b.d.e = 4;

console.log(complexObj.b.d.e); // ?
console.log(copy.b.d.e); // ?

🎉 You now understand object references, shallow copies, deep copies, and ways to implement them! Keep practicing to write safer, more efficient frontend code.