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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Immutability in JavaScript — When and Why Should You Use It
  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • Detection and Mitigation of Lateral Movement in Cloud Networks
  • Docker Base Images Demystified: A Practical Guide
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  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!

By 
Janki Mehta user avatar
Janki Mehta
·
Feb. 27, 23 · Analysis
Likes (3)
Comment
Save
Tweet
Share
3.3K 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.

Related

  • Immutability in JavaScript — When and Why Should You Use It
  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!