1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Deep Copy: structuredClone vs JSON vs Spread, Tested

A JavaScript deep copy duplicates an object and everything nested inside it, so changing the copy never touches the original. Compare spread, Object.assign, the JSON trick, structuredClone and a custom function on dates, Maps, Sets, BigInt, circular references and classes, with real Node.js output and timings.

9 min read
JavaScript deep copy: structuredClone vs JSON vs spread, tested

Key takeaways

  • Spread ({...obj}) and Object.assign are shallow: nested objects stay shared.
  • The JSON trick turns Dates into strings, Sets and Maps into {}, drops undefined, turns NaN into null, and throws on BigInt and cycles.
  • structuredClone keeps Dates, Maps, Sets, BigInt, undefined, NaN and circular references, but drops class prototypes and throws on functions.
  • In our Node.js 24 test, the JSON trick was actually faster for plain data; choose by correctness first.

You copy an order object, change the quantity in the copy, and the original order changes too. Every JavaScript developer hits this once. Objects are assigned by reference, and most “copy” techniques only copy the top level. A JavaScript deep copy creates fully independent nested data, and since 2022 the language has a built-in way to do it. Each technique still has trade-offs, so we tested them side by side.

All examples ran in Node.js v24.22.1 and the output is shown as printed. structuredClone works the same in modern browsers. If spread syntax is new to you, start with our spread operator guide.

Shallow copy vs deep copy

A shallow copy creates a new outer object but copies references to anything nested inside, so both objects point at the same inner arrays and objects. A deep copy recursively copies every level. Primitive values such as numbers and strings are always copied, because they are immutable.

Our test object

const order = {
  id: 1,
  items: [{ sku: "A1", qty: 1 }],
  created: new Date("2026-11-22T10:00:00Z"),
  tags: new Set(["new"]),
  meta: new Map([["src", "web"]]),
  note: undefined,
  total: NaN,
  big: 10n ** 20n,
};

It deliberately contains the types that break naive copies: nested arrays, a Date, a Set, a Map, an undefined property, NaN and a BigInt.

Spread and Object.assign: shallow only

const s = { ...order };
s.items[0].qty = 99;
console.log(order.items[0].qty);              // 99  (original changed!)

const o2 = Object.assign({}, order);
console.log(o2.items === order.items);        // true (same array)

Both create a new top-level object, so s.id = 2 would not affect order. But items is the same array in both, so changing a nested item changes the original. Shallow copies are perfect for flat objects and for immutable update patterns where you copy each level you change, as in { ...order, items: [...order.items, newItem] }.

The JSON trick: JSON.parse(JSON.stringify(x))

JSON.parse(JSON.stringify(order));
// TypeError: Do not know how to serialize a BigInt

const { big, ...noBig } = order;
const j = JSON.parse(JSON.stringify(noBig));
typeof j.created      // 'string'
JSON.stringify(j.tags) // '{}'
JSON.stringify(j.meta) // '{}'
"note" in j            // false
j.total                // null

Serialising to text and back produces new objects at every level, which is why this trick was popular for years. But it only understands JSON’s types. Our Date became a string, the Set and Map became empty objects, the undefined property disappeared, NaN became null, and BigInt threw an error. Functions are silently dropped, and a circular reference throws TypeError. It is safe only for data that is already plain JSON, such as an API response.

structuredClone: the built-in deep copy

const sc = structuredClone(order);
sc.created instanceof Date   // true
sc.tags instanceof Set       // true
sc.meta.get("src")           // 'web'
"note" in sc                 // true
sc.total                     // NaN
sc.big                       // 100000000000000000000n

sc.items[0].qty = 5;
order.items[0].qty           // 1  (original untouched)

structuredClone uses the same algorithm browsers use to send data to Web Workers and store it in IndexedDB. It handles Dates, RegExps, Maps, Sets, typed arrays, ArrayBuffers, BigInt, undefined, NaN and Error objects. It is a global in modern browsers and in Node.js 17 and later, with no import or library needed.

Circular and shared references

const a = { name: "a" };
a.self = a;
const ac = structuredClone(a);
ac.self === ac   // true  (cycle rebuilt inside the copy)
ac.self !== a    // true  (not pointing at the original)
JSON.stringify(a)   // TypeError (circular structure)

const shared = { x: 1 };
const two = structuredClone({ a: shared, b: shared });
two.a === two.b  // true  (shared reference preserved)

Real data often contains cycles, such as a parent with children that point back to the parent. structuredClone rebuilds the same graph shape inside the copy: an object referenced twice in the original is still one object referenced twice in the copy. The JSON trick fails on cycles, and on shared references it would silently create two separate copies.

What structuredClone cannot copy

structuredClone({ fn() {} });
// DataCloneError: fn() {} could not be cloned.

class Money { constructor(v) { this.v = v; } fmt() { return `₹${this.v}`; } }
const m = structuredClone(new Money(5));
m instanceof Money     // false
m.constructor.name     // 'Object'
typeof m.fmt           // 'undefined'

Object.isFrozen(structuredClone(Object.freeze({ k: 1 })))   // false
  • Functions throw a DataCloneError.
  • Class instances come back as plain objects: data is copied, methods and the prototype are lost.
  • Property descriptors are not kept: getters become plain values, and frozen objects come back unfrozen.
  • DOM nodes cannot be cloned (use node.cloneNode(true)), and Symbols as values throw.

If your state is plain data, these limits rarely matter. If it holds class instances, see the next section or rebuild instances from the cloned data. Our JavaScript classes guide covers prototypes.

A custom deep copy that keeps classes

function deepCopy(v, seen = new WeakMap()) {
  if (v === null || typeof v !== "object") return v;
  if (seen.has(v)) return seen.get(v);
  if (v instanceof Date) return new Date(v);
  const out = Array.isArray(v) ? [] : Object.create(Object.getPrototypeOf(v));
  seen.set(v, out);
  for (const k of Reflect.ownKeys(v)) out[k] = deepCopy(v[k], seen);
  return out;
}

const mc = deepCopy(new Money(7));
mc instanceof Money   // true
mc.fmt()              // '₹7'

Keeping the prototype preserves methods, and the WeakMap handles cycles. This short version does not handle Maps, Sets or typed arrays, which is exactly why hand-written deep copy functions tend to grow bugs. Libraries such as Lodash’s cloneDeep cover more cases; we did not run Lodash here.

Comparison table

Feature Spread / assign JSON trick structuredClone
Nested objects copied No Yes Yes
Date stays a Date Shared Becomes string Yes
Map and Set Shared Become {} Yes
undefined, NaN Yes Dropped, null Yes
BigInt Yes Throws Yes
Circular references Shared Throws Yes
Functions Shared Dropped Throws
Class prototype Lost Lost Lost

Performance

Test (Node.js 24, best of 5) structuredClone JSON round trip
20,000 nested objects 26.6 ms 14.0 ms
100,000 tiny objects, one at a time 181 ms 53 ms

For plain JSON-shaped data, the JSON round trip was faster in our runs, because V8’s JSON functions are heavily optimised and structuredClone does more bookkeeping for types and cycles. Older articles report the opposite for large objects, which shows how engine versions change these numbers. Either way, copying 20,000 objects took well under 30 ms. Choose the method that is correct for your data, and only optimise if profiling shows copying is a real cost.

Tip: if you deep-copy large state on every change, consider structural sharing instead: copy only the path you modify and reuse the rest.

Do you need a deep copy at all?

Often the better answer is not to mutate. Immutable update patterns copy only the levels you change:

const updated = { ...order,
  items: order.items.map(i => i.sku === "A1" ? { ...i, qty: 2 } : i) };

This creates a new order and a new item while sharing everything unchanged. This is how React and Redux state updates are usually written, and it is faster than copying everything. Destructuring makes these updates shorter.

Which deep copy method should you use?

  • Plain JSON data (API responses, config): structuredClone, or the JSON trick if you also want to strip non-JSON values.
  • Data with Dates, Maps, Sets, BigInt or cycles: structuredClone.
  • Class instances: a custom copy or a clone() method on the class.
  • Flat objects or one-level updates: spread.
  • Frequently updated large state: immutable updates with structural sharing.

Python developers will recognise the same split between copy.copy and copy.deepcopy; see our Python deepcopy guide.

Final thoughts

A JavaScript deep copy is only as good as its handling of your data types. Spread is shallow, the JSON trick silently corrupts Dates, Maps, Sets and special numbers, and structuredClone handles almost everything except functions and class prototypes. Make structuredClone your default, keep the JSON trick for strictly JSON data, write a custom copy when classes matter, and avoid copying altogether with immutable updates when you can.

Frequently asked questions

How do I deep copy an object in JavaScript?

Use the built-in structuredClone function, for example const copy = structuredClone(original). It copies nested objects, arrays, Dates, Maps, Sets and circular references.

Is the spread operator a deep copy?

No. Spread creates a shallow copy, so nested objects and arrays are still shared between the original and the copy.

What is wrong with JSON parse and stringify for copying?

It converts Dates to strings, turns Maps and Sets into empty objects, drops undefined and functions, turns NaN into null and throws on BigInt and circular references.

Does structuredClone copy class instances?

It copies their data but not their prototype, so the result is a plain object without the class methods. Use a custom copy or a clone method for class instances.

Is structuredClone faster than JSON?

Not always. In our Node.js 24 test the JSON round trip was faster for plain data. structuredClone is chosen for correctness, because it supports many more types.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →