What is a deep copy?

A deep copy duplicates an object and everything nested inside it, so the copy shares no references with the original and can be changed freely without side effects.

The modern way: structuredClone

Available in all modern browsers, Node.js 17+, Deno and Bun.

  • Handles nested objects and arrays, Date, Map, Set, RegExp, typed arrays, ArrayBuffer, Error, Blob and more.
  • Handles circular references.
  • Does not copy functions, DOM nodes or class identity (instances become plain objects). It throws a DataCloneError for functions and symbols.

JSON.parse(JSON.stringify(obj))

The old trick. It only works for plain JSON data: it turns dates into strings, drops undefined and functions, converts NaN to null, loses Map/Set, and throws on circular references.

Library or custom

Lodash's cloneDeep handles more cases (including keeping prototypes). A custom recursive clone gives full control, for example to preserve class instances. Writing one is a common interview exercise (see "Deep clone an object").

When to deep copy

  • Before mutating data you do not own (a cached API response, a config object).
  • To snapshot state for undo, history or tests.

When not to

Deep copying large structures is expensive. For UI state updates, copying only the path you change (structural sharing) is faster and keeps unchanged references stable for memoisation.

Code example

js
1const original = {
2 name: "Ada",
3 joined: new Date("2024-01-01T00:00:00Z"),
4 roles: new Set(["admin"]),
5 settings: { theme: "dark", shortcuts: ["ctrl+s"] },
6};
7original.self = original; // circular reference
8
9const copy = structuredClone(original);
10copy.settings.theme = "light";
11copy.settings.shortcuts.push("ctrl+z");
12copy.roles.add("editor");
13
14console.log(original.settings.theme, original.settings.shortcuts); // dark ["ctrl+s"]
15console.log(original.roles.size, copy.roles.size); // 1 2
16console.log(copy.joined instanceof Date, copy.self === copy); // true true
17
18// The JSON trick loses information and fails on cycles
19const flat = { joined: new Date(0), missing: undefined, nan: NaN };
20console.log(JSON.parse(JSON.stringify(flat))); // { joined: "1970-01-01T00:00:00.000Z", nan: null }
21try {
22 JSON.stringify(original);
23} catch (e) {
24 console.log(e.name); // TypeError (circular structure)
25}
26
27// structuredClone cannot copy functions
28try {
29 structuredClone({ fn() {} });
30} catch (e) {
31 console.log(e.name); // DataCloneError
32}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app