Deep Copy vs Shallow Copy

Published by Brayan K

A deep copy duplicates an object along with all the nested objects it contains, creating a fully independent clone, whereas a shallow copy only copies the top level and still shares references to nested values.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Specify which relationships the copy must preserve

Copying has more than one goal: preserve a list’s order while sorting a new list, edit one nested branch, duplicate a supported data graph, or extract a small domain snapshot. Those goals need different operations. Start by checking identity at each level instead of assuming a new outer object makes all nested data independent.

const original = { title: "Board", tags: ["study"] };
const copy = { ...original }; // Copy the top-level properties.
copy.title = "Draft"; // This property is on the new outer object.
copy.tags.push("review"); // This array is still shared.
console.log(original.title, copy.title);
console.log(original === copy, original.tags === copy.tags);
console.log(original.tags.join(","));

// ✅ Expected output:
// Board Draft
// false true
// study,review

Assignment without a copying operation would share the outer object too. Spread copies property values; a nested object value is still a reference to that nested object. Spread & Rest Operators owns spread syntax. Pure Functions, Immutability & Side Effects owns updating a changed path while intentionally sharing unchanged branches.

Choose a shallow copy when it matches the operation

const records = [{ id: "A", rank: 2 }, { id: "B", rank: 1 }];
const sorted = records.slice().sort((a, b) => a.rank - b.rank);
console.log(records.map(record => record.id).join(","), sorted.map(record => record.id).join(","));
console.log(sorted[0] === records[1]);
sorted[0].rank = 9;
console.log(records[1].rank);

// ✅ Expected output:
// A,B B,A
// true
// 9

The copied array protects the original order, not the record contents. If a consumer needs to edit those records independently, that is a stronger requirement. Document it rather than claiming slice or spread always makes a safe editable copy.

Structured cloning preserves supported graph relationships

const shared = { tags: ["study"] };
const original = { first: shared, second: shared };
original.self = original;
const copy = structuredClone(original);
console.log(copy !== original, copy.first !== original.first);
console.log(copy.first === copy.second, copy.self === copy);
copy.first.tags.push("review");
console.log(original.first.tags.join(","), copy.second.tags.join(","));

// ✅ Expected output:
// true true
// true true
// study study,review

The clone separates these ordinary objects from the source while preserving the fact that first and second refer to one shared object inside the cloned graph. Its self link points to the clone. A naive recursive copier without a visited-object map can lose that alias relationship or recurse forever on a cycle.

const original = {
  date: new Date("2000-01-01T00:00:00Z"),
  values: new Set([2, 3]),
  lookup: new Map([["A", { score: 7 }]])
};
const copy = structuredClone(original);
console.log(copy.date instanceof Date, copy.date.getUTCFullYear());
console.log(copy.values instanceof Set, copy.values.has(3));
console.log(copy.lookup instanceof Map, copy.lookup.get("A").score);
copy.lookup.get("A").score = 9;
console.log(original.lookup.get("A").score, copy.lookup.get("A").score);

// ✅ Expected output:
// true 2000
// true true
// true 7
// 7 9

The date is fixed input, not the current clock. Support is type-specific: structuredClone is not a promise to duplicate every capability or every object’s implementation details. Check the supported-type contract for data crossing the boundary.

const key = { id: "A" };
const original = { key, map: new Map([[key, "saved"]]) };
const copy = structuredClone(original);
console.log(copy.key === key);
console.log(copy.map.has(key), copy.map.get(copy.key));
console.log([...copy.map.keys()][0] === copy.key);

// ✅ Expected output:
// false
// false saved
// true

The cloned Map contains a cloned object key. Looking it up with the original key fails because object keys use identity. Copy the connected graph together when its internal relationships must stay connected. Map & Set owns those collection lookup rules.

A structured clone is not a clone of arbitrary behaviour

try {
  structuredClone({ value: 3, run() { return 4; } });
} catch (error) {
  console.log(error.name);
}

// ✅ Expected output:
// DataCloneError

The runtime throws DataCloneError for this unsupported function. The caught program prints the actual error name because full messages can include a representation of the function and vary between engines. Select the data fields you need or define a reconstruction protocol; do not silently discard required behaviour.

class Task {
  constructor(title) { this.title = title; }
  label() { return this.title.toUpperCase(); }
}
const original = new Task("Arrays");
const copy = structuredClone(original);
console.log(original instanceof Task, copy instanceof Task);
console.log(copy.title, typeof copy.label);
console.log(Object.getPrototypeOf(copy) === Object.prototype);

// ✅ Expected output:
// true false
// Arrays undefined
// true

The copied data is not a newly constructed Task with its original class behaviour. Private elements and custom prototype chains are not recreated by this operation. Prototype Chain & Advanced OOP Patterns owns descriptors, inherited behaviour and method-copying limits.

let reads = 0;
const original = {};
Object.defineProperty(original, "value", {
  enumerable: true,
  get() { reads++; return 7; }
});
Object.defineProperty(original, "hidden", { value: 9, enumerable: false });
const copy = structuredClone(original);
const descriptor = Object.getOwnPropertyDescriptor(copy, "value");
console.log(reads, copy.value);
console.log(typeof descriptor.get, descriptor.writable);
console.log(Object.hasOwn(copy, "hidden"));

// ✅ Expected output:
// 1 7
// undefined true
// false

This is a data-copy operation that can evaluate an enumerable getter, not a descriptor-preserving clone with no observable work. The getter’s returned value becomes an ordinary data property in this fixture. Keep accessors and arbitrary external objects outside a plain-data snapshot contract when their evaluation would be surprising.

JSON round trips change the data model

const object = { kept: 1, missing: undefined, fn: () => 2, notFinite: NaN };
const array = [undefined, () => 2, NaN, Infinity];
console.log(JSON.stringify(object));
console.log(JSON.stringify(array));
console.log(JSON.stringify(new Map([["A", 1]])));

// ✅ Expected output:
// {"kept":1,"notFinite":null}
// [null,null,null,null]
// {}

Without a custom replacer or toJSON, undefined and function-valued object properties disappear; array entries become null, and non-finite numbers become null. A Map does not automatically serialize its entries as an object. JSON is a text data format with its own contract, not a general deep-clone API.

JSON.stringify({ value: 3n });

// ✅ Expected error:
// TypeError: Do not know how to serialize a BigInt
const original = { name: "A" };
original.self = original;
try { JSON.stringify(original); }
catch (error) { console.log(error.name); }
const copy = structuredClone(original);
console.log(copy.self === copy);

// ✅ Expected output:
// TypeError
// true

The TypeError is checked by name because cycle diagnostics can include multi-line property paths. A custom JSON encoding can deliberately represent references or special types, but then encoding and decoding become part of the application’s explicit protocol.

Copying a buffer and transferring a buffer are different contracts

const original = new Uint8Array([1, 2, 3]);
const copy = structuredClone(original);
copy[0] = 9;
console.log([...original].join(","), [...copy].join(","));
console.log(original.buffer === copy.buffer);

// ✅ Expected output:
// 1,2,3 9,2,3
// false
const original = new Uint8Array([1, 2, 3]);
const copy = structuredClone(original, { transfer: [original.buffer] });
console.log(original.byteLength, original.buffer.byteLength);
console.log([...copy].join(","), copy.byteLength);

// ✅ Expected output:
// 0 0
// 1,2,3 3

The transfer list moves the supported underlying resource instead of leaving a usable original buffer. That is intentional ownership transfer, not a harmless copy. These examples use ordinary ArrayBuffer; shared-memory objects have a different sharing contract. Web Workers (Background Threads) owns message passing and worker ownership decisions.

Guided exercise: observe separation and preserved aliasing

Fill the literal hints to clone one connected graph. The two references inside the clone should still agree with each other while being separate from the source object.

const shared = { value: 1 };
const original = { first: shared, second: shared };
const copy = ___(original); // 👉 replace ___ with structuredClone
copy.first.value = ___; // 👉 replace ___ with 2
console.log(original.first.value, copy.second.value);
console.log(copy.first === copy.___); // 👉 replace ___ with second

// ✅ Expected output:
// 1 2
// true

Independent brief: extract an editable task snapshot

Write snapshotTasks(tasks) for a plain array of plain task records. Each task requires a unique non-empty string id, a string title, a boolean complete and an array of string tags. Reject invalid records with TypeError("invalid task"), duplicate ids with Error("duplicate task id"), and a non-array input with TypeError("tasks must be an array"). Treat ids literally; do not trim or otherwise normalize them.

Return only id, title, complete and tags. Create a new outer array, a new record and a new tags array for every task. Even if two input tasks share one tags array, their snapshot tags must be independent from each other. Ignore extra fields such as a save callback; this is a domain projection, not a clone of every property. Check both directions of mutation, shared input tags, ignored fields, an empty list, duplicate ids, wrong tag types and missing array slots.

function snapshotTasks(tasks) {
  if (!Array.isArray(tasks)) throw new TypeError("tasks must be an array");
  const ids = new Set();
  return Array.from(tasks, task => {
    if (task === null || typeof task !== "object" ||
        typeof task.id !== "string" || task.id.length === 0 ||
        typeof task.title !== "string" || typeof task.complete !== "boolean" ||
        !Array.isArray(task.tags) ||
        Array.from(task.tags).some(tag => typeof tag !== "string")) {
      throw new TypeError("invalid task");
    }
    if (ids.has(task.id)) throw new Error("duplicate task id");
    ids.add(task.id);
    return { id: task.id, title: task.title, complete: task.complete, tags: task.tags.slice() };
  });
}
const tags = ["study"];
const source = [
  { id: "a", title: "Arrays", complete: false, tags, save() {} },
  { id: "b", title: "Objects", complete: true, tags }
];
const copy = snapshotTasks(source);
console.log(copy !== source, copy[0] !== source[0]);
console.log(copy[0].tags !== tags, copy[0].tags !== copy[1].tags);
copy[0].tags.push("review");
copy[0].title = "Changed";
console.log(source[0].title, source[0].tags.join(","), copy[1].tags.join(","));
source[1].complete = false;
tags.push("source-only");
console.log(copy[1].complete, copy[1].tags.join(","));
console.log(Object.keys(copy[0]).join(","), snapshotTasks([]).length);
for (const invalid of [
  [source[0], source[0]],
  [{ ...source[0], tags: [1] }],
  [{ ...source[0], tags: Array(1) }],
  Array(1),
  null
]) {
  try { snapshotTasks(invalid); } catch (error) { console.log(error.name, error.message); }
}

// ✅ Expected output:
// true true
// true true
// Arrays study study
// true study
// id,title,complete,tags 0
// Error duplicate task id
// TypeError invalid task
// TypeError invalid task
// TypeError invalid task
// TypeError tasks must be an array

Reference notes

The structuredClone reference covers cycles and transfer. Its algorithm guide lists supported types and limitations. The JSON.stringify reference describes the different serialization rules.

Practice quiz

What does this complete program print? const source={nested:{value:1}};const copy={...source}; copy.nested.value=2; console.log(source.nested.value,copy===source);

  • 2 false
  • 1 false
  • 2 true
  • 1 true

Answer: 2 false. A new outer object still shares its nested value.

What does this complete program print? const shared={value:1};const source={a:shared,b:shared}; const copy=structuredClone(source); console.log(copy.a===copy.b,copy.a===shared);

  • false false
  • true false
  • true true
  • false true

Answer: true false. Cloning the connected graph preserves its internal alias while separating it from the source.

What does this complete program print? const source={};source.self=source; const copy=structuredClone(source); console.log(copy.self===copy,copy.self===source);

  • false false
  • true true
  • true false
  • false true

Answer: true false. The cloned cycle points to the cloned object.

What does this complete program print? console.log(JSON.stringify({a:undefined,b:1}));

  • {"a":null,"b":1}
  • {"a":"undefined","b":1}
  • {}
  • {"b":1}

Answer: {"b":1}. Undefined object properties are omitted by ordinary JSON serialization.

What does this complete program print? console.log(JSON.stringify([undefined,NaN]));

  • [null,null]
  • []
  • [undefined,NaN]
  • {}

Answer: [null,null]. These array values become null in JSON.

What does this complete program print? class Item{constructor(){this.value=1} read(){return this.value}} const copy=structuredClone(new Item()); console.log(copy.value,typeof copy.read);

  • 1 function
  • 1 undefined
  • undefined function
  • undefined undefined

Answer: 1 undefined. The custom prototype method is not recreated.

What does this complete program print? const source=new Uint8Array([1,2]); const copy=structuredClone(source,{transfer:[source.buffer]}); console.log(source.byteLength,copy.byteLength);

  • 2 2
  • 0 0
  • 0 2
  • 2 0

Answer: 0 2. Transferring the buffer detaches the original while the transferred copy retains two bytes.

What does this complete program print? const key={};const source={key,map:new Map([[key,7]])}; const copy=structuredClone(source); console.log(copy.map.has(key),copy.map.get(copy.key));

  • true 7
  • false undefined
  • true undefined
  • false 7

Answer: false 7. The cloned map uses its cloned key, whose identity differs from the source key.

Continue this course

Related lessons