Programming Language
JavaScript
Shallow and Deep Copy

Understanding Shallow and Deep Copy in JavaScript

Introduction

In JavaScript, copying objects and arrays is a common task, but it can be a bit tricky because there are different types of copies: shallow copy and deep copy. Understanding these concepts is crucial for managing data and avoiding unintended changes in your programs.

This article will explain what shallow and deep copies are, how they differ, and provide examples to help you understand how to use them.

Shallow Copy

A shallow copy creates a new object or array, but it only copies the top level of the structure. If the object or array contains other objects or arrays, the references to these nested structures are copied, not the actual nested data. This means changes to nested objects or arrays in the copied structure will affect the original structure.

How to Create a Shallow Copy

  • Using Object.assign() for objects:
  const original = { name: 'Alice', age: 25 };
  const shallowCopy = Object.assign({}, original);
  
  console.log(shallowCopy); // Output: { name: 'Alice', age: 25 }

Using spread syntax for objects:

const original = { name: 'Bob', age: 30 };
const shallowCopy = { ...original };
 
console.log(shallowCopy); // Output: { name: 'Bob', age: 30 }

Using slice() for arrays:

const originalArray = [1, 2, 3, 4];
const shallowCopyArray = originalArray.slice();
 
console.log(shallowCopyArray); // Output: [1, 2, 3, 4]

Using spread syntax for arrays:

const originalArray = [5, 6, 7, 8];
const shallowCopyArray = [...originalArray];
 
console.log(shallowCopyArray); // Output: [5, 6, 7, 8]

Example of Shallow Copy

const original = { name: 'Charlie', hobbies: ['reading', 'gaming'] };
const shallowCopy = { ...original };
 
shallowCopy.hobbies.push('hiking');
 
console.log(original.hobbies); // Output: ['reading', 'gaming', 'hiking']
console.log(shallowCopy.hobbies); // Output: ['reading', 'gaming', 'hiking']

In this example, modifying the hobbies array in shallowCopy also affects the original object because the nested array is shared between both objects.

Deep Copy

A deep copy creates a new object or array, along with all nested objects and arrays. This means that all levels of the structure are copied, and changes to any part of the copied structure do not affect the original structure. Deep copy is useful when you need a completely independent clone of an object or array.

How to Create a Deep Copy

Using JSON.parse() and JSON.stringify():

const original = { name: 'Diana', hobbies: ['swimming', 'cycling'] };
const deepCopy = JSON.parse(JSON.stringify(original));
 
console.log(deepCopy); // Output: { name: 'Diana', hobbies: ['swimming', 'cycling'] }

Note: This method does not work with functions, undefined, and special objects like Date.

Using a custom deep copy function:

function deepCopy(obj) {
  return JSON.parse(JSON.stringify(obj));
}
 
const original = { name: 'Eve', address: { city: 'New York', zip: '10001' } };
const copied = deepCopy(original);
 
copied.address.city = 'Los Angeles';
 
console.log(original.address.city); // Output: 'New York'
console.log(copied.address.city); // Output: 'Los Angeles'

Example of Deep Copy

const original = { name: 'Frank', details: { age: 28, skills: ['JavaScript', 'Node.js'] } };
const deepCopy = JSON.parse(JSON.stringify(original));
 
deepCopy.details.skills.push('React');
 
console.log(original.details.skills); // Output: ['JavaScript', 'Node.js']
console.log(deepCopy.details.skills); // Output: ['JavaScript', 'Node.js', 'React']

In this example, modifying the skills array in deepCopy does not affect the original object because the entire structure was copied deeply.

Key Differences

Shallow Copy:

  • Copies only the top level of the structure.
  • Nested objects or arrays are shared between the original and copied structures.
  • Useful for simple, non-nested data.

Deep Copy:

  • Copies all levels of the structure, including nested objects and arrays.
  • The original and copied structures are completely independent.
  • Useful for complex data structures.

Conclusion

Understanding the difference between shallow and deep copy is important for managing data in JavaScript. Shallow copies are useful for simple cloning where nested data isn't a concern, while deep copies are essential for creating fully independent copies of complex data structures. By using these methods appropriately, you can avoid unintended side effects and ensure your data remains consistent in your JavaScript applications.