liveBook · Manning

Copy

As explained in JavaScript in Depth

A copying technique that recursively duplicates an object and the objects reachable from it.

A deep copy duplicates an object and its reachable data, but the copying method determines its costs. JSON roundtripping creates a serialized string and then a second object graph; during parsing, both remain alive, potentially tripling the data’s memory footprint. The string can also be much larger than the original graph. section 9.4.1

Choose a copying strategy based on what must be preserved:

  • Use structuredClone for deep copies that need to handle circular references, typed arrays, bigint values, or Date objects. section 9.4.1
  • Extract only the needed properties when a full duplicate is unnecessary; avoiding needless copies reduces work for the garbage collector. section 9.4.1
const copy = JSON.parse(JSON.stringify(original));

JSON roundtrip deep-copy pattern. section 9.4.1

const copy = structuredClone(original);

structuredClone alternative. section 9.4.1

How JavaScript in Depth covers it

How deep it goes
Traces JSON serialization and parsing through simultaneous memory use, but does not detail clone implementation internals.
Examples
Compares JSON.parse/stringify with structuredClone and cites a 1 MB graph producing a 3 MB string.
What you can do after
Evaluate whether a full deep copy is necessary and choose between structuredClone and direct property extraction.
How it connects
Connects deep cloning to JSON serialization, structuredClone, object graphs, and garbage collection.

Also explained in

Compare how 7 books explain copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.