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
const copy = structuredClone(lesson);
Example
Interactive preview availableconst 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
- The lesson has a nested seats array.
- structuredClone copies the nest, not just the outer object.
- Changing the copy seat number leaves the original at 1.
- Changing the copy title leaves the original title.
- The page prints both so you can see they diverged.
- Dates and maps can clone too.
- Functions and DOM nodes cannot.
- 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.