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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript
  • Singleton: 6 Ways To Write and Use in Java Programming
  • A Comprehensive Guide To Working With JSON in JavaScript

Trending

  • Data Contracts as the "Circuit Breaker" for Model Reliability
  • How SaaS Architectures Break at Scale — and the Engineering Decisions That Prevent It
  • Optimizing High-Volume REST APIs Using Redis Caching and Spring Boot (With Load Testing Code)
  • How to Save Money Using Custom LLMs for Specific Tasks
  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.7K 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

  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript
  • Singleton: 6 Ways To Write and Use in Java Programming
  • A Comprehensive Guide To Working With JSON in JavaScript

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook