DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. JavaScript
  4. Shallow and Deep Copies in JavaScript: What’s the Difference?

Shallow and Deep Copies in JavaScript: What’s the Difference?

Understand the difference between shallow and deep copies in JavaScript, when each is best applied, and how to implement them. Get your quick overview here!

Janki Mehta user avatar by
Janki Mehta
·
Feb. 27, 23 · Analysis
Like (2)
Save
Tweet
Share
2.09K Views

Join the DZone community and get the full member experience.

Join For Free

Have you ever tried to create a duplicate of an object in JavaScript, but the output wasn’t what you expected? If so, this article will discuss the different techniques for cloning and how to correctly utilize them. This knowledge will help guarantee that you get the correct results whenever you use the clone command.

In JavaScript, we can also create shallow copies and deep copies of objects. Let’s dive into what each of these concepts means in JavaScript.

Shallow Copy

A shallow copy in JavaScript creates a new object that contains references to the same memory locations as the original object. This means that if any changes are made to the copied object, the original object is also affected.

In JavaScript, there are several ways to create a shallow copy:

Object.assign()

The Object.assign() method copies all enumerable properties of an object to a new object. It takes one or more source objects and a target object. The target object is the object that will be modified and returned. Here’s an example:

 
let originalObj = { name: "John", age: 30 };
let copiedObj = Object.assign({}, originalObj);

copiedObj.age = 40;

console.log(originalObj.age); // Output: 40


As you can see, changing the age property of the copied object also changes the age property of the original object.

Spread Operator

The spread operator (...) can also be used to create a shallow copy of an object. This operator spreads the properties of an object into a new object. Here’s an example:

 
let originalObj = { name: "John", age: 30 };
let copiedObj = { ...originalObj };

copiedObj.age = 40;

console.log(originalObj.age); // Output: 40


Again, changing the age property of the copied object also changes the age property of the original object. 

Deep Copy

A deep copy creates a new object with all the properties and sub-properties of the original object. This means that any changes made to the copied object will not affect the original object.

In JavaScript, there are several ways to create a deep copy:

JSON.parse() and JSON.stringify()

The easiest way to create a deep copy of an object is to use JSON.parse() and JSON.stringify(). Here’s an example:

 
let originalObj = { name: "John", age: 30, address: { city: "New York", state: "NY" } };
let copiedObj = JSON.parse(JSON.stringify(originalObj));

copiedObj.address.city = "Los Angeles";

console.log(originalObj.address.city); // Output: New York


As you can see, changing the city property of the copied object does not affect the city property of the original object.

Recursion

Another way to create a deep copy is to use recursion to copy all the properties of the original object and any sub-objects. Here’s an example:

 
function deepCopy(obj) {
  let copiedObj = Array.isArray(obj) ? [] : {};

  for (let key in obj) {
    if (typeof obj[key] === "object" && obj[key] !== null) {
      copiedObj[key] = deepCopy(obj[key]);
    } else {
      copiedObj[key] = obj[key];
    }
  }

  return copiedObj;
}

let originalObj = { name: "John", age: 30, address: { city: "New York", state: "NY" } };
let copiedObj = deepCopy(originalObj);

copiedObj.address.city = "Los Angeles";

console.log(originalObj.address.city); // Output: New York


In this example, the deepCopy() function recursively copies all the properties and sub-properties of the original object. Any changes made to the copied object do not affect the original object. 

Conclusion

In conclusion, understanding the difference between shallow copy and deep copy in JavaScript is important for proper object manipulation and memory management.

A shallow copy creates a new object that shares the same memory references as the original object. Any changes made to the shallow copy or original object will affect both objects. A shallow copy can be useful for creating references to existing objects without consuming more memory.

On the other hand, a deep copy creates a new object that is entirely independent of the original object. Any changes made to the deep copy will not affect the original object and vice versa. A deep copy can be useful for creating entirely new objects that are not dependent on the original object.

The choice between shallow copy and deep copy depends on the requirements of the code and the desired outcome. A shallow copy is useful when dealing with large objects that need to be referenced multiple times, while a deep copy is useful when creating new, independent objects that are not dependent on the original object.

Cloning JavaScript Memory (storage engine) OBJ (programming language) Object (computer science) Property (programming) Object type (object-oriented programming)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DevOps vs Agile: Which Approach Will Win the Battle for Efficiency?
  • Understanding and Solving the AWS Lambda Cold Start Problem
  • The Power of Zero-Knowledge Proofs: Exploring the New ConsenSys zkEVM
  • Building the Next-Generation Data Lakehouse: 10X Performance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: