Understanding JavaScript Deep Copy and Shallow Copy

When working with objects and arrays in JavaScript, it's crucial to understand the difference between shallow copy and deep copy. These methods are used to duplicate objects, but they handle nested structures differently, which can lead to unexpected behavior if not properly understood.

Shallow Copy

A shallow copy creates a new object or array, but it does not recursively copy nested objects or arrays. Instead, it copies the reference to the nested objects or arrays. This means that changes made to the nested objects in the shallow copy will also affect the original object.

Example with Objects:

// Original object
const original = {
    name: 'John',
    address: {
        city: 'New York',
        country: 'USA'
    }
};

// Shallow copy using Object.assign
const shallowCopy = Object.assign({}, original);

// Modify the shallow copy
shallowCopy.name = 'Doe';
shallowCopy.address.city = 'Los Angeles';

// Outputs
console.log(original.name);          // 'John' (unchanged)
console.log(original.address.city);  // 'Los Angeles' (changed)

Example with Arrays:

// Original array
const originalArray = [1, 2, { a: 3 }];

// Shallow copy using spread operator
const shallowCopyArray = [...originalArray];

// Modify the shallow copy
shallowCopyArray[0] = 9;
shallowCopyArray[2].a = 5;

// Outputs
console.log(originalArray[0]);       // 1 (unchanged)
console.log(originalArray[2].a);     // 5 (changed)

Deep Copy

A deep copy creates a new object or array and recursively copies all nested objects and arrays. This ensures that the copy is completely independent of the original, and changes to the copy do not affect the original object.

Example with Objects:

// Original object
const original = {
    name: 'John',
    address: {
        city: 'New York',
        country: 'USA'
    }
};

// Deep copy using JSON methods
const deepCopy = JSON.parse(JSON.stringify(original));

// Modify the deep copy
deepCopy.name = 'Doe';
deepCopy.address.city = 'Los Angeles';

// Outputs
console.log(original.name);          // 'John' (unchanged)
console.log(original.address.city);  // 'New York' (unchanged)

Example with Arrays:

// Original array
const originalArray = [1, 2, { a: 3 }];

// Deep copy using JSON methods
const deepCopyArray = JSON.parse(JSON.stringify(originalArray));

// Modify the deep copy
deepCopyArray[0] = 9;
deepCopyArray[2].a = 5;

// Outputs
console.log(originalArray[0]);       // 1 (unchanged)
console.log(originalArray[2].a);     // 3 (unchanged)

Considerations

Understanding when to use shallow copy versus deep copy is key to effectively managing JavaScript objects and arrays:

Other Methods for Deep Copy

While the JSON methods are commonly used, there are other ways to perform a deep copy in JavaScript:

When to Use

Choosing between shallow copy and deep copy depends on your specific use case. For most simple applications, a shallow copy may suffice. However, if you're dealing with complex data structures or need to ensure that your copied objects are fully independent, a deep copy is the way to go.

Published By: Krishanu Jadiya
Updated at: 2024-08-15 01:24:19

Card Image

Ultimate Guide to Setting Up PHP Development Environment with Apache on Ubuntu 20.04

Comprehensive guide to setting up a PHP development environment using Apache on Ubuntu 20.04. Includes step-by-step instructions, installation of dependencies, SSL configuration, and setting up Laravel with Composer.

Card Image

Setup PHP Laravel Environment with Docker: Apache, Ubuntu, and MongoDB

Guide to setting up a PHP Laravel environment with Docker, including configuration for Apache, Ubuntu, and MongoDB.

Card Image

Setting Up CI/CD Pipeline for Laravel on GitLab with AWS EC2 Deployment

Guide to setting up a CI/CD pipeline for a Laravel project on GitLab, including deploying to an AWS EC2 instance and configuring SSH keys for remote access to a Git repository.

Card Image

Top 50 Docker Interview Questions and Answers

Prepare for your next DevOps interview with these top 50 Docker interview questions, designed to help you understand and master Docker's core concepts and practices.