← Back to JavaScript, page 1

javascript-0018 · Medium mid

What is the difference between a shallow copy and a deep copy, and how do you make a deep copy?

A shallow copy duplicates only the top level, so nested objects are still shared with the original. A deep copy duplicates every level, so the two values are fully independent. structuredClone is the built-in way to deep copy plain data, including dates, maps, sets, and circular references, but not functions.

Full answer

Objects and arrays are stored by reference. When a value is copied with { ...obj }, Object.assign, slice(), or [...arr], the engine creates a new outer container and copies the references found inside. Primitive fields are copied by value, but nested objects are the very same objects in both copies. Changing a nested field through one copy is visible through the other.

A deep copy walks through all levels and creates new objects at each one. These are the common options:

  • structuredClone(value) is built into modern browsers and Node.js 17 and later. It handles Date, Map, Set, RegExp, typed arrays, and circular references. It throws a DataCloneError for functions, and class instances lose their prototype and become plain objects.
  • JSON.parse(JSON.stringify(value)) is a quick trick for plain data, but it turns dates into strings, drops undefined and functions, converts NaN to null, loses Map and Set, and throws on circular references.
  • A custom recursive function gives full control, but it must handle arrays, dates, cycles, and special objects.
  • Libraries such as Lodash provide cloneDeep.

In many real cases, a full deep copy is not needed. Copying only the path that changes, as UI state libraries do, is cheaper and keeps unchanged parts shared.

javascript
const order = {
  id: 7,
  placedAt: new Date('2026-01-15T10:00:00Z'),
  items: [{ name: 'Notebook', qty: 2 }],
  tags: new Set(['school']),
};

const shallow = { ...order };
shallow.items[0].qty = 99;
console.log('original after shallow change:', order.items[0].qty);

order.items[0].qty = 2;
const deep = structuredClone(order);
deep.items[0].qty = 5;
console.log('original after deep change:', order.items[0].qty);
console.log('date kept as Date:', deep.placedAt instanceof Date);
console.log('set kept as Set:', deep.tags instanceof Set);

const viaJson = JSON.parse(JSON.stringify(order));
console.log('JSON date type:', typeof viaJson.placedAt);
console.log('JSON set value:', JSON.stringify(viaJson.tags));

const loop = { name: 'loop' };
loop.self = loop;
console.log('structuredClone keeps cycle:', structuredClone(loop).self.self.name);
try {
  JSON.stringify(loop);
} catch (error) {
  console.log('JSON.stringify on a cycle:', error.name);
}
try {
  structuredClone({ run() {} });
} catch (error) {
  console.log('function:', error.name);
}

Run with Node.js v24.22.1 as js-18.js; two runs gave identical output. Output: original after shallow change: 99 original after deep change: 2 date kept as Date: true set kept as Set: true JSON date type: string JSON set value: {} structuredClone keeps cycle: loop JSON.stringify on a cycle: TypeError function: DataCloneError

Key points

  • Shallow copies share nested objects; deep copies do not.
  • Spread, Object.assign, slice, and Array.from make shallow copies.
  • structuredClone is the modern deep copy for plain data and handles cycles.
  • JSON round trips lose dates, undefined, functions, Map, and Set, and fail on cycles.
  • Copying only what changes is often better than a deep copy.

Common mistakes

  • Believing spread or Object.assign copies nested objects.
  • Using the JSON trick on data with dates, undefined, Map, or Set and silently corrupting it.
  • Expecting structuredClone to keep class methods; the copy is a plain object.
  • Deep copying a huge object on every update when only one branch changed.

Follow-ups

  • How would you write a deepClone function that handles circular references?
  • How do immutable updates in a UI library avoid deep copies?
  • What does structuredClone do with a class instance and its prototype?

Tips

  • Start with the reference idea; it makes the whole topic easy to explain.
  • Name at least two ways to deep copy and one limit for each.
  • If asked to write deepClone, mention a WeakMap to track visited objects for cycles.