Sobes.tech
Middle+

How to copy an object in JavaScript? How does shallow copy differ from deep copy?

sobes.tech AI

Answer from AI

In JavaScript, there are several ways to copy an object:

  1. Shallow copy:
  • Object.assign({}, obj) — copies only the top-level properties.
  • Spread operator: { ...obj }
  1. Deep copy:
  • Recursively copying all nested objects.
  • Using JSON.parse(JSON.stringify(obj)) — a simple method, but it doesn't work with functions, dates, undefined, etc.
  • Specialized libraries, such as lodash (_.cloneDeep(obj))

Difference:

  • Shallow copy copies only the first level of properties. If the object contains nested objects, only references to them are copied, not the objects themselves.
  • Deep copy creates a fully independent copy, including all nested objects.

Example of shallow copy:

const original = { a: 1, b: { c: 2 } };
const copy = { ...original };
copy.b.c = 3;
console.log(original.b.c); // 3 — the original also changed because b is a reference

Example of deep copy with JSON:

const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.b.c = 3;
console.log(original.b.c); // 2 — the original did not change
How to copy an object in JavaScript? How does shallow… - sobes.tech