Home > Web Front-end > JS Tutorial > body text

Shallow Copy vs Deep Copy in JavaScript

WBOY
Release: 2024-07-26 20:45:00
Original
511 people have browsed it

Shallow Copy vs Deep Copy in JavaScript

When working with JavaScript, understanding the difference between shallow copy and deep copy is essential for effective manipulation of objects and arrays. Let's delve into what these terms mean and how to implement each type of copy in your code.

Shallow Copy
A shallow copy creates a new object or array that holds the same values as the original. However, if the original contains nested objects or arrays, the shallow copy only copies the references to these nested structures, not the structures themselves. This means changes to the nested objects or arrays in the copied structure will also affect the original.

Examples of Shallow Copy Methods:

  1. Spread Operator ({...})
const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };
Copy after login

Here, shallowCopy is a new object, but shallowCopy.b still references the same object as original.b.

2.Object.assign()

const shallowCopy = Object.assign({}, original);
Copy after login
  1. Array slice Method
const originalArray = [1, 2, 3];
const shallowCopyArray = originalArray.slice();
Copy after login

Deep Copy
A deep copy creates a new object or array that is a complete, independent clone of the original, including all nested objects and arrays. Changes to the deep copy do not affect the original and vice versa.

Examples of Deep Copy Methods:

  1. JSON.stringify() and JSON.parse()
const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));
Copy after login

This method serializes the object to a JSON string and then parses it back to a new object. However, it does not handle functions, undefined, or circular references.

2.Recursive Function

function deepCopy(obj) {
  if (obj === null || typeof obj !== 'object') return obj;

  const copy = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      copy[key] = deepCopy(obj[key]);
    }
  }
  return copy;
}

Copy after login
  1. StructuredClone() (in modern JavaScript environments)
const deepCopy = structuredClone(original);
Copy after login

When to Use Each

  • Shallow Copy: Suitable for simple objects or arrays without nested structures. It's faster and uses less memory. Use it when you need a quick copy where changes to nested objects should reflect in both the original and the copy.

  • Deep Copy: Necessary for complex objects or arrays with nested structures. It ensures that changes to the copy do not affect the original. Use it when you need completely independent clones.

Understanding these differences helps prevent bugs that arise from unintended shared references and ensures data integrity in your applications

The above is the detailed content of Shallow Copy vs Deep Copy in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!