Shallow Copy vs Deep Copy in JavaScript: Key Differences Explained

Harish Kumar · · 1863 Views
Shallow Copy vs Deep Copy in JavaScript: Key Differences Explained

When working with objects and arrays in JavaScript, it's crucial to understand the difference between shallow copy and deep copy. These concepts dictate how data is duplicated and whether changes to the copied data affect the original.

1. Shallow Copy

A shallow copy duplicates an object's first level properties. However, if the object contains references (like nested objects or arrays), the references themselves are copied—not the values they point to. This means changes to nested properties in the copied object will reflect in the original.

Example:

const original = {
  name: "Alice",
  address: {
    city: "Wonderland",
    zip: "12345"
  }
};

// Creating a shallow copy
const shallowCopy = { ...original };

// Modifying the nested object
shallowCopy.address.city = "Looking Glass";

// Both objects are affected
console.log(original.address.city); // Output: "Looking Glass"
console.log(shallowCopy.address.city); // Output: "Looking Glass"

Methods to Create Shallow Copies:

- Using the spread operator (...):

const shallowCopy = { ...originalObject };

- Using Object.assign():

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

2. Deep Copy

A deep copy duplicates all properties, including nested objects and arrays. It creates entirely independent objects, ensuring changes to the copy do not affect the original.

Example:

const original = {
  name: "Alice",
  address: {
    city: "Wonderland",
    zip: "12345"
  }
};

// Creating a deep copy
const deepCopy = JSON.parse(JSON.stringify(original));

// Modifying the nested object
deepCopy.address.city = "Looking Glass";

// Only the copy is affected
console.log(original.address.city); // Output: "Wonderland"
console.log(deepCopy.address.city); // Output: "Looking Glass"

Methods to Create Deep Copies:

  1. Using JSON.stringify() and JSON.parse():- Converts the object to a JSON string and back.- Limitations:     - Does not handle circular references.     - Ignores non-JSON-safe data like functions, undefined, Symbol, etc.

  2. Using a Custom Recursive Function:- Write a function to recursively copy properties.

  3. Using Libraries:
    -  Popular libraries like Lodash provide deep cloning methods:

const _ = require("lodash");
const deepCopy = _.cloneDeep(originalObject);

Key Differences

Feature

Shallow Copy 

Deep Copy

Nested References 

Retained (shared with the original) 

Fully duplicated (independent)

Performance

Faster 

Slower (due to recursion or iteration)

Usage

Simple structures 

Complex or deeply nested structures

When to Use Which?

  1. Shallow Copy:- When working with flat objects or when changes to nested data are intentional.- Example: Copying configuration objects with minimal nesting.

  2. Deep Copy:
    - When dealing with deeply nested objects and ensuring independence is critical.
    - Example: Cloning application state in Redux or immutability in  React.

Understanding and choosing the right approach helps avoid bugs and unintended side effects in your JavaScript applications.

👉 Download Javascript: from ES2015 to ES2023 - eBook

Shallow Copy vs Deep Copy in JavaScript: Key Differences Explained
0

Please login or create new account to add your comment.

0 comments
You may also like:

15 Must-Know TypeScript Features to Level Up Your Development Skills

TypeScript has become the go-to tool for developers building scalable, maintainable JavaScript applications. Its advanced features go far beyond basic typing, giving developers (...)
Harish Kumar

JavaScript Best Practices: Tips for Writing Clean and Maintainable Code

JavaScript is one of the most versatile and widely used programming languages today, powering everything from simple scripts to complex web applications. As the language continues (...)
Harish Kumar

Ditch jQuery: Vanilla JS Alternatives You Need to Know

jQuery revolutionized web development by simplifying DOM manipulation, event handling, and animations. However, modern JavaScript (ES6 and beyond) now provides many built-in methods (...)
Harish Kumar

A Beginner’s Guide to Efficient Memory Use in JavaScript

Managing memory efficiently in JavaScript applications is essential for smooth performance, especially for large-scale or complex applications. Poor memory handling can lead to (...)
Harish Kumar

Exploring the New Features of JavaScript ES2024: A Look into the Future of Web Development

Discovering new functionality in programming languages is a bit like a holiday — it’s filled with anticipation and the excitement of exploring something new. With the proposed (...)
Harish Kumar

Understanding the `.reduce()` Method in JavaScript

The .reduce() method in JavaScript is one of the most powerful array methods used for iterating over array elements and accumulating a single value from them. Whether you're summing (...)
Harish Kumar