Understanding Deep vs Shallow Copy in JavaScript: A Comprehensive Guide

RMAG news

When working with JavaScript, understanding the differences between deep and shallow copies is crucial for managing data structures effectively. Whether you’re handling arrays, objects, or other data types, knowing how to copy them correctly can prevent unexpected behavior and bugs in your code. In this article, we’ll explore what deep and shallow copies are, how they differ, and when to use each type.

What is a Shallow Copy?
A shallow copy of an object is a copy whose properties share the same references as those in the original object. If the object contains nested objects, the references to those nested objects are copied, not the nested objects themselves. This means that changes to the nested objects in the copy will also affect the original object.

Example

const original = { a: 1, b: { c: 2 } };
const shallowCopy = { …original };

shallowCopy.b.c = 3;

console.log(original.b.c); // Output: 3

In the example above, modifying shallowCopy.b.c also modifies original.b.c because shallowCopy and original share the same reference to the nested object b.

What is a Deep Copy?
A deep copy of an object is a copy that duplicates all levels of the original object’s properties. This means that nested objects are also copied, not just their references. Changes to the deep copy do not affect the original object and vice versa.

Example

const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));

deepCopy.b.c = 3;

console.log(original.b.c); // Output: 2

In this example, modifying deepCopy.b.c does not affect original.b.c because deepCopy is a completely separate copy of original.

Methods to Create Shallow Copies

1.Object Spread Operator ({…}):

const shallowCopy = { …original };

2.Array slice Method:

const originalArray = [1, 2, 3];
const shallowCopyArray = originalArray.slice();

3.Object.assign method

const shallowCopy = Object.assign({}, original);

Methods to Create Deep Copies
1.JSON.parse and JSON.stringify:

const deepCopy = JSON.parse(JSON.stringify(original));

Note: This method has limitations, such as not handling functions or undefined properties.

2.Recursive function

function deepCopy(obj) {
if (obj === null || typeof obj !== ‘object’) return obj;

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

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

return copy;
}

3.Using Libraries:
Libraries like Lodash offer utility functions for deep cloning.

const _ = require(‘lodash’);
const deepCopy = _.cloneDeep(original);

When to Use Deep vs Shallow Copy

Shallow Copy:
Use when you need a copy of an object where changes to nested objects should reflect in both the original and the copy.
Suitable for simple objects without nested structures.

Deep Copy:
Use when you need a completely independent copy of an object, especially if it contains nested objects.
Essential for complex data structures to avoid unintended side effects.

Understanding deep and shallow copies is fundamental for JavaScript developers. It helps ensure data integrity and prevents bugs that arise from unintended shared references. By knowing when and how to use each type of copy, you can write more robust and maintainable code.