JavaScript Intermediate Language Basics · 6 min read

structuredClone for a Real Copy

Lesson 28 of 38 in the JavaScript learning path.

How do I copy a lesson object without sharing nested arrays?

structuredClone deep-copies structured data, including nested arrays and dates.

A spread copy is shallow. Editing copy.seats[0] would still edit the original after a spread.

Syntax & Parameters

Syntax
const copy = structuredClone(lesson);

Example

Interactive preview available
app.js
const lesson = {
  title: "Routes",
  seats: [{ row: "A", n: 1 }]
};
const copy = structuredClone(lesson);
copy.seats[0].n = 4;
copy.title = "Routes draft";
const out = document.querySelector("#out");
out.textContent = [
  "original " + lesson.title + " seat " + lesson.seats[0].n,
  "copy " + copy.title + " seat " + copy.seats[0].n
].join(" | ");

Expected Output

original Routes seat 1 | copy Routes draft seat 4

Line-by-Line Walkthrough

  1. The lesson has a nested seats array.
  2. structuredClone copies the nest, not just the outer object.
  3. Changing the copy seat number leaves the original at 1.
  4. Changing the copy title leaves the original title.
  5. The page prints both so you can see they diverged.
  6. Dates and maps can clone too.
  7. Functions and DOM nodes cannot.
  8. Do not use JSON parse as a clone if you have dates or undefined.

Common Pitfalls & Security

structuredClone is not a universal copier.

  • Functions on the object throw DataCloneError.
  • DOM nodes cannot be cloned this way.
  • A shallow spread still shares nested arrays.
  • JSON stringify drops undefined and converts dates to strings.

Best Practices & Modern Standards

Clone before you mutate a cached lesson for a draft form.

Keep functions outside the data object so the payload stays cloneable.

Real-World Use

The editor clones the published lesson into a draft. Changing the draft seat map does not change the live lesson until save.

Frequently Asked Questions

Is this a deep copy?

Yes for structured cloneable data such as objects, arrays, and dates.

What throws?

Functions, symbols as object keys in some cases, and DOM nodes.

Why not the spread operator?

Spread copies one level. Nested arrays stay shared.

Why not JSON?

JSON drops undefined and turns dates into strings.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…